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>
)
Latest comments (2)
This is nice, i was stuck trying to implement this. Thanks to your article, it helped a great deal. @atosh502
Nice, I'd give it a try.