[SOLVED] React native, the useEffect on a object state not working

Issue

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

Solution

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

Answered By – jperl

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.