Set default values in react-hook-form

atosh502

Aashutosh Poudel

Posted on January 13, 2023

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:

💖 💪 🙅 🚩
atosh502
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