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

edyucheng picture edyucheng · Jun 7, 2020 · Viewed 29.2k times · Source

I am creating a page for user to update personal data with React-Hook-Form. Once paged is loaded, I use useEffect to fetch the user's current personal data and set them into default value of the form.

I put the fetched value into defaultValue of <Controller />. However, it is just not showing in the text box. Here is my code:

The called API is working well and the value is actually set to userData state.

{
  name: "John",
  phone: "02-98541566"
  ...
}

I also tried to setUserData with mock data in useEffect(), and it doesn't work either. Is there any problem in my above code?

Answer

tommcandrew picture tommcandrew · Jun 7, 2020

You can use setValue (https://react-hook-form.com/api/useform/setvalue).

Import it from useForm:

    const { handleSubmit, control, setValue} = useForm({mode: 'onBlur'});

Then call it with the user data after it's received:

  useEffect(() => {
    if (userData) {
      setValue([{ name: userData.name }, { phone: userData.phone }]);
    }
  }, [userData]);

You can remove the default values from the form.

EDIT: See alternative answers below if this does not work.