ste9206
ste9206

Reputation: 1892

React hooks form: reset or setValue when updating form first time from props?

I am in a child component, which receives customer prop from its parent component.

So I want to update the form with values coming from customer, so I have done this:

useEffect(() => {
    let isMounted = true;
    if (isMounted) {
      reset({
        firstname: customer.firstname,
        lastname: customer.lastname,
        address: {
          street: customer.address.street,
          city: customer.address.city,
          country: customer.address.country,
        },
      });
    }

    return () => {
      isMounted = false;
    };
}, [customer, reset]);

but actually, I noticed that it's not changing properly the values inside the address nested object (street and city are updated, country is not).

However, if I am using setValue, it will update the value accordingly. So my question is: which one between reset() and setValue() should be used for this specific case?

Thanks

Upvotes: 2

Views: 4145

Answers (1)

Mehul Thakkar
Mehul Thakkar

Reputation: 2437

Based on your use case you have to use reset and you're doing a correct thing there but may be the country dropdown/selector fall in the below mentioned case as per react-hook-form documentation. (Read the first line)

For controlled components like React-Select which do not expose a ref prop, you will have to reset the input value manually with setValue or connect your component via useController or Controller.

I believe this piece of code is correct but the code example of form will help to understand the context in a much better way.

Upvotes: 1

Related Questions