I have a very simple implementation of a counter. On form submit, the value of the counter is always "0". The counter value is changing but I am not sure why on form submit, the counter value is 0.
I am not sure, what I am missing. Thank you for your time.
Below is my code:
import React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit } = useForm();
const [quantity, setQuantity] = React.useState(0);
const decrement = () => {
setQuantity((prev) => (prev === 0 ? 0 : prev - 1));
};
const increment = () => {
setQuantity((prev) => prev + 1);
};
const formSubmit = (data) => console.log(data);
return (
<div className="App">
<h1>Counter</h1>
<form onSubmit={handleSubmit(formSubmit)}>
<button type="button" onClick={decrement}>
-
</button>
<input type="number" value={quantity} {...register("quantity")} />
<button type="button" onClick={increment}>
+
</button>
<button type="submit">Submit</button>
</form>
</div>
);
}
2
Answers
This might help you out
Furthermore details Here
your code not works due to useForm use register(
onChange,name,onBlur
) for input and you are using quantity of useSate instead ofuseForm
defaultValuesIf you want to do using useForm then you can do by using
setValue,getValues
anddefaultValues
in this wayHope this helps you out