React - Checkbox returning undefined value on first time

Viewed 1600

I have a functional component and I'm trying to get the value from a checkbox input, but even if I set a initial state the first value that I get from the console is undefined. It only starts to retrieve the value from the state after I click a second time.

const Preferences = () => {

    const [pref, setPref] = useState({
        webcam: true
    });


    const onChange = e => {

        setPref({ ...pref, [e.target.name]: e.target.checked });

        console.log(webcam); //always undefined on first time
    };

...
<input
    type="checkbox"
    name="webcam"
    value={webcam}
    onChange={onChange}
    defaultChecked={webcam}
/>
1 Answers

It's undefined the first time because your state is named perf with a property webcam.

Correctly access your state properties when passing values as props.

<input
    type="checkbox"
    name="webcam"
    value={perf.webcam}
    onChange={onChange}
    defaultChecked={perf.webcam}
/>

Also, trying to console log state directly after queueing up an update doesn't work as react state updates are asynchronous in nature and occur between render cycles, i.e. it simply logs the state value from the current render cycle. Use an effect to log the updated state values.

Additionally, due to the asynchronous nature of react state updates and nullable synthetic events, you'll likely want to grab the event's name and checked value so the event isn't nullified and returned to the event pool before the state update is processed.

const Preferences = () => {

    const [pref, setPref] = useState({
        webcam: true
    });

    useEffect(() => {
        console.log(perf.webcam);
    }, [perf]);

    const onChange = e => {
        const { checked, name } = e.target;
        setPref({ ...pref, [name]: checked });
    };

...
Related