skip to Main Content

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


  1. useEffect is called after the component was rendered. So when the code reaches that line the first time around, it tries to read null.from.

    Maybe you’d want to move all that which is inside the useEffect inside useState, as the default value. You don’t actually need a useEffect here.

    const [HHDays, setHHDays] = useState(props.infos.happy ?
                {
                    allWeek: { from: props.infos.ending, to: props.infos.strating, showPickerFrom: false, showPickerTo: false },
                }
                :
                {
                    allWeek: { from: "", to: "", showPickerFrom: false, showPickerTo: false },
                });
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. Try passing an empty object to useState instead of null

    const [HHDays, setHHDays] = useState({});

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search