React function a step behind in state

28 Views Asked by At

when using the react hook form watch api to follow the state of a form field, i'm trying to dynamically manipulate the values of the data so that i can limit the number of checked boxes to 3. i attempted this by watching the value and storing it in a variable named 'toggles', i then call a function on a click event, inside the function, check whether that element already exists in the form data, if it does remove (so we are toggling), else add it to the array. i'm using the form hook 'setValue' to set the form value. The issue i'm having is the value of the variable i've stored my selected items in, is always one step behind it's true state! help!!

this is the use of the watch api to watch for the 'select' input values

const toggles = watch('select', []);

this is my on click function, setValues...

{brochures && brochures.map((brochure, index) => {
  return (
    <div key={brochure.code + index}>
      <div onClick={() => setValues(brochure.code)}>
        <span>
          <input
            {...register("select")}
            type='checkbox'
            value={brochure.code}
            id={brochure.code}
            disabled={
              toggles.length >= 3 && !toggles.includes(brochure.code)
                ? true
                : false
            }
          />
          <label>Order Now</label>
          {brochure && brochure.new && <span>NEW</span>}
        </span>
        <img src={brochure.image + "?width=300"}></img>
      </div>
    </div>
  );
})}

----- and the function it calls

const setValues = (code: string) => {
  let updateSelectedOptions;

  if (toggles.length <= 3) {
    if (toggles.includes(code)) {
      updateSelectedOptions = toggles.filter(function (brochure) {
        return brochure !== code;
      });
      setValue("select", updateSelectedOptions);
    } else {
      updateSelectedOptions = [...toggles, code];
      setValue("select", updateSelectedOptions);
    }
  }
};

i've tried setting in state the form values, instead of using the watch hook, however the problem persists

0

There are 0 best solutions below