score:1

Accepted answer

You can use watch to keep track of the field value in the render lifecycle and setValue to update the form value imperatively:

const { register, watch, handleSubmit, setValue } = useForm({
  defaultValues: {
    quantity: 0
  }
});
const quantity = watch("quantity");
const increaseQuantity = () => setValue("quantity", quantity + 1);
const decreaseQuantity = () => {
  if (quantity > 1) {
    setValue("quantity", quantity - 1);
  }
};

useEffect(() => {
  console.log(quantity);
}, [quantity]);

return (
  <form onSubmit={handleSubmit((data) => alert(JSON.stringify(data)))}>
    <button type="button" onClick={decreaseQuantity}>
      -
    </button>
    <button type="button" onClick={increaseQuantity}>
      +
    </button>
    <input {...register("quantity")} id="quantity" type="number" />

    <input type="submit" />
  </form>
);

Codesandbox Demo

References


Related Query

More Query from same tag