DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

Set default values in react-hook-form

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]);
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
)
Enter fullscreen mode Exit fullscreen mode

 

Resources and code snippets taken from:

Latest comments (2)

Collapse
 
micahbala profile image
Micah Bala

This is nice, i was stuck trying to implement this. Thanks to your article, it helped a great deal. @atosh502

Collapse
 
fagbenjaenoch profile image
Enoch Fagbenja

Nice, I'd give it a try.