0

I am facing problem while updating check box state using React hooks, By default check box is false.

Below code sample

function GPSPosition() {
   const [isEnable, setCheckBoxEnable] = useState(false)
   
   const enableStopSendingData = (e) => {
        e.preventDefault();
        setCheckBoxEnable(e.target.checked) 
        console.log(e.target.checked);// on check of CheckBox, here value is `true`

        console.log(isEnable); // true is not set to isEnable, value here is `false`
   }


   return (
                <div className="text-ellipsis">{GpsConstants.WIDGET_NAME}</div>
                    <Checkbox checked={isEnable} onChange={(checked) => enableStopSendingData(checked)} 
                  className="homepage-widget-checkbox text-ellipsis" >{HomepageConst.CHECKBOX_HEADER} 
                   </Checkbox>
                </div>
   )
}

1

3 Answers 3

1

setCheckBoxEnable is the asynchronous method so you can't get the updated value of isEnable immediately after setCheckBoxEnable().

        setCheckBoxEnable(e.target.checked) 
        console.log(isEnable); // This will show old value of `isEnable`

You should use useEffect with adding isEnable dependency to check the updated state value.

useEffect(() => {
  console.log(isEnable);
}, [isEnable]);
Sign up to request clarification or add additional context in comments.

Comments

1

From your code it seems checkbox should work fine, but in case you need updated value after setting in state, you could use useEffect.

    useEffect(() => {
      // Here you will get latest value
    }, [stateVeriable]);

1 Comment

Yes i used useEffect, it worked Thank you
0

delete th this line: e.preventDefault();

reference Event/preventDefault

1 Comment

Even after removing this line it does not work, the above answer from William worked

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.