Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

checkbox state is not updating on spot

On save, I want to proceed with a function depending if a checkbox have been ticked or not. If the checkbox have been ticked, the function should proceed with the save, otherwise it should display a warning that the checkbox needs to be checked.

However, my functionality is not working. I noticed that if I console.log the checkbox boolean from the state, the state wasn’t updated at the time I am calling the function.


  const [checkBoxTick, setCheckBoxTick] = useState(false);
  const [checkBoxError, setCheckBoxError] = useState(false);


  const onSave = useCallback(async () => {
    console.log(checkBoxTick);
    if (checkBoxTick) {
        *** go ahead and save ****
    } else {
      setCheckBoxError(true);
    }
  }, []);


  <Checkbox
    label="text here"
    helperText="This field is required"
    error={checkBoxError}
    onChange={() => setCheckBoxTick(!checkBoxTick)}
  />


   <Button color="primary" size="small" onClick={onSave}>
       Save
  </Button>

When I check the checkBox (which changes the state of checkBoxTick to true) and hit the button, the function gets called but the state of checkBoxTick is false although it should be true.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know its a common state problem and the whole internet is recommending using useEffect(), but I couldn’t make sense of how to use it in my case.

Any help is much appreciated 🙂

Thank you in advance.

>Solution :

UseCallback is memoizing the state of checkBoxTick. You need to pass the variable as a dependency to useCallback so that it gets updated, like so:

  const onSave = useCallback(async () => {
    console.log(checkBoxTick);
    if (checkBoxTick) {
        *** go ahead and save ****
    } else {
      setCheckBoxError(true);
    }
  }, [checkBoxTick]);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading