Home > Enterprise >  Record a changing input field in react-hook-form?
Record a changing input field in react-hook-form?

Time:10-23

I'm trying to record values from a form using react-hook-form. All other situations are working, however I am getting a return value of 'undefined' when I attempt to retrieve data from a value that is also a react hook (useState).

const [quantity, setQuantity] = useState(1);

const increaseQuantity = () => {
  setQuantity((prevQuantity) => prevQuantity   1);
};

const decreaseQuantity = () => {
  if (quantity > 1) {
    setQuantity((prevQuantity) => prevQuantity - 1);
  }
};

const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
  console.log(data);
};
<DescriptionButtonsWrapper>
  <CounterContainer>
    <CounterWrapper>
      <CounterButtons onClick={decreaseQuantity}>-</CounterButtons>
    </CounterWrapper>
    <CounterWrapper>
      <CounterInput
        {...register("quantity")}
        placeholder="Quantity"
        id="quantity"
        type="number"
      >
        {quantity}
      </CounterInput>
    </CounterWrapper>
    <CounterWrapper>
      <CounterButtons onClick={increaseQuantity}> </CounterButtons>
    </CounterWrapper>
  </CounterContainer>
</DescriptionButtonsWrapper>
<DescriptionButtonsWrapper>
  <Btn onClick={handleSubmit(onSubmit)}>Add to Cart</Btn>
</DescriptionButtonsWrapper>

CodePudding user response:

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