Here is the code before the render
const HappyComponent = (props) => {
console.log(JSON.stringify(props)); // the props are ok
const [HHDays, setHHDays] = useState(null);
useEffect(() => {
const hours = props.infos.happy ?
{
allWeek: { from: props.infos.ending, to: props.infos.strating, showPickerFrom: false, showPickerTo: false },
}
:
{
allWeek: { from: "", to: "", showPickerFrom: false, showPickerTo: false },
}
setHHDays(hours);
console.log(JSON.stringify(HHDays));
}, []);
return (
So the state
of HHDays
stays null
and the render shows an error on the frist {HHDays.allWeek.from}
TypeError: null is not an object (evaluating ‘HHDays.allWeek’)
3
Answers
useEffect
is called after the component was rendered. So when the code reaches that line the first time around, it tries to readnull.from
.Maybe you’d want to move all that which is inside the
useEffect
insideuseState
, as the default value. You don’t actually need auseEffect
here.SetState is an asynchronous call, meaning, its unclear if the state is changed when the code reaches the log. If you need to make sure the state is set, you can use a timeout or a useeffect based on state changes.
Try passing an empty object to useState instead of null
const [HHDays, setHHDays] = useState({});