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

北城余情 提交于 2020-12-06 04:39:17

问题


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:

import React, {useState, useEffect, useCallback} from 'react';
import { useForm, Controller } from 'react-hook-form'
import { URL } from '../constants';

const UpdateUserData = props => {
    const [userData, setUserData] = useState(null);
    const { handleSubmit, control} = useForm({mode: 'onBlur'});

    const fetchUserData = useCallback(async account => {
        const userData = await fetch(`${URL}/user/${account}`)
                            .then(res=> res.json());
        console.log(userData);
        setUserData(userData);
    }, []);

    useEffect(() => {
        const account = localStorage.getItem('account');
        fetchUserData(account);
    }, [fetchUserData])

    const onSubmit = async (data) => {
        // TODO
    }

    return (
        <div>
            <form onSubmit={handleSubmit(onSubmit)}>
                <div>
                    <label>User Name:</label>
                    <Controller
                        as={<input type='text' />}
                        control={control}
                        defaultValue={userData ? userData.name : ''}
                        name='name'
                    />
                </div>
                
                <div>
                    <label>Phone:</label>
                    <Controller
                        as={<input type='text' />}
                        control={control}
                        defaultValue={userData ? userData.phone : ''}
                        name='phone'
                    />
                </div>
                <button>Submit</button>
            </form>
        </div>
    );
}

export default UpdateUserData;

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?


回答1:


So using setValue (https://react-hook-form.com/api#setValue), import the setValue function from useForm:

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

Then call it with the user data after you receive the userData:

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

You can remove the default values from the form. I hope this works!




回答2:


setValue doesn't work for me. Alternatively, you can use the reset method. I am sharing a working code block below. I hope it works for you.

  ...
  /* registered address */
  const [registeredAddresses, setRegisteredAddresses] = useState([]);
  
  const { register, errors, handleSubmit, reset } = useForm<FormProps>({
    validationSchema: LoginSchema,
  });

  /**
   * get addresses data
   */
  const getRegisteredAddresses = async () => {
    try {
      const addresses = await AddressService.getAllAddress();
      setRegisteredAddresses(addresses);
      setDataFetching(false);
    } catch (error) {
      setDataFetching(false);
    }
  };

  useEffect(() => {
    getRegisteredAddresses();
  }, []);

  useEffect(() => {
    if (registeredAddresses) {
      reset({
        addressName:
          registeredAddresses: registeredAddresses[0].name,

        tel: registeredAddresses[0].contactNumber,
      });
    }
  }, [registeredAddresses]);

  ...



回答3:


@tommcandrew's setValue parameter formatting didn't work for me.

This format did:

useEffect(() => {
  const object = localStorage.getItem('object');
  setValue("name", object.name);
}, [])


来源:https://stackoverflow.com/questions/62242657/how-to-change-react-hook-form-defaultvalue-with-useeffect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!