reactjsreact-hook-form

Set default values in React Hook Form


I want to check in a RHF if the user has modified the form values with the isDirty parameter.

Setting the defaultValues manually works:

const {handleSubmit, control, setValue, setError, setFocus} = useForm({defaultValues: {name: ""}});

This seem to work correctly.

But when the user tries to edit a form I load the values into the form with setValue.

Now I don't know how I can set programatically the defaultValues.

How to change React-Hook-Form defaultValue with useEffect()?

This is how I do, but the answer is not really correct. The values are set, but the defaultValues don't change this way so RHF can't compare.

Make sure to provide all inputs' defaultValues at the useForm, so hook form can have a single source of truth to compare whether the form is dirty.

https://react-hook-form.com/api/useform/formstate

How can I set the defaultValues dynamically so it even works in 'edit' mode?


Solution

  • It would be easier for you to use reset() to set the defaultValue of your form. Here's an example on CodeSandbox I have prepared for you.

    All you have to do is to create an object inside useEffect(). Set your all default values using that object. At last spread that defaultValues object inside reset().

      useEffect(() => {
        let defaultValues = {};
        defaultValues.firstName = "Kristof";
        defaultValues.lastName = "Rado";
        reset({ ...defaultValues });
      }, []);
    
      <input {...register("firstName")} placeholder="First Name" />
      <input {...register("lastName")} placeholder="Last Name" />