5

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
  • 3
    Wouldn't you be accessing your webcam value from pref.webcam? Commented Jul 29, 2020 at 0:32

1 Answer 1

4

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

...
Sign up to request clarification or add additional context in comments.

1 Comment

After an hour of searching, your suggestion to pull out checked and name before calling setPref... that solved my issue. Great suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.