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
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
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
)
}
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;
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
a?.propsi.e. Optional Chaining