Set default values in react-hook-form
Aashutosh Poudel
Posted on January 13, 2023
Data is fetched from an api or some async operation, and reset
is used to set the default values for the form.
const { reset } = useForm();
useEffect(() => {
// you can do async server request and fill up form
setTimeout(() => {
reset({
firstName: "bill",
lastName: "luo"
});
}, 2000);
}, [reset]);
Or if we need to partially update the form, we can pass a function to the reset
function like so.
<button
onClick={() => {
reset(formValues => ({
...formValues,
lastName: 'test',
}))
}}
>
Reset partial
</button>
Alternatively, we can use setValue
to set a few form fields
const { register, setValue } = useForm();
return (
<form>
<input {...register("firstName")} />
<button type="button" onClick={()=> setValue("firstName", "Bill")}>
setValue
</button>
</form>
)
Resources and code snippets taken from:
💖 💪 🙅 🚩
Aashutosh Poudel
Posted on January 13, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
reacthookform Testing a mui Date Picker Adaptor Component Integrated with React Hook Form
January 21, 2022