Home > Net >  React native, the useEffect on a object state not working
React native, the useEffect on a object state not working

Time:08-05

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')

CodePudding user response:

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 },
            });

CodePudding user response:

Try passing an empty object to useState instead of null

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

CodePudding user response:

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.

  • Related