1

I have a view. Its sample code is

const [a, seta] = useState(null)
useEffect(() => {
        if(!a){

            geta(match.params.id);
        }
    })
return (
a.props
);

But it is giving error can't read property of null value

1

2 Answers 2

1

Why the Error?

Your code returns a.props before useEffect assigns a a value. Effectively you are returning props of null, hence the error.

"By default, effects run after every completed render" - React docs

How to Fix

You could conditionally return the data: return(a && a.props ? a.props : null)

For an example in context, something like this should work:

const [a, seta] = useState(null)
  useEffect(() => {
          if(!a){
              seta({greeting: 'Hello World'});
          }
      })
  return (
    a && a.greeting ? a.greeting : null
  )
}
Sign up to request clarification or add additional context in comments.

Comments

1

The following code returns an error because a is null on the first render, prior to useEffect kicking in and updating a's value.

import React, { useState, useEffect } from 'react';

const App = () => {

  const [a, seta] = useState(null)
  useEffect(() => {
    /*  ... do what you need to do */
  }, [])

  return (
    <div className="App">
      <h1>Your state:</h1>
      <h2>{a.props}</h2>
    </div>
  );
}

export default App;

The observed error statement


Instead, add a type guard in your return function to prevent a null value before useEffect fires:

import React, { useState, useEffect } from "react";

const App = () => {
  const [a, seta] = useState(null);
  useEffect(() => {
    /*  ... do what you need to do */
    setTimeout(() => seta({ props: 'test'}), 3000);
  }, []);

  return (
    <div className="App">
      <h1>Your state:</h1>
      {/* <h2>{a.props}</h2> // an erroneous return value */}
      <h2>{a !== null && a.props !== null ? a.props : "Loading ..."}</h2>
    </div>
  );
};

export default App;

Working CodeSandbox: https://codesandbox.io/s/stack-66736637-nullinreturn-6or9f

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.