Home > Enterprise >  checkbox state is not updating on spot
checkbox state is not updating on spot

Time:04-25

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.

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.

CodePudding user response:

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

  • Related