29

I have the following interface :

export interface DataResponse {
  user_id: string;
  name: string;
  phone_number: string;
  country: string;
}

which is used as a type for fetching the data with react query. I am using useEffect to populate the fields if there is data:

useEffect(() => {
    if (userData) {
      Object.entries(userData).forEach(
        ([name, value]) => setValue(name, value));
    }
}, [setValue, userData]);

The type of userData is DataResponse... when I set the values with setState(name, value) it underlines name and throws the following error:

Argument of type 'string' is not assignable to parameter of type | "name" | "phone_number" | "country"
2
  • 1
    Why you want to update the state while iterating the object ? is setValue for updating a local state ? If so just do setValue(userData) and treat your state as an object. Commented Dec 8, 2021 at 0:06
  • Its react hook form function Commented Dec 8, 2021 at 0:16

4 Answers 4

45

I think you can just use RHF's reset method here.

useEffect(() => {
    if (userData) {
      reset(userData);
    }
}, [userData, reset]);
Sign up to request clarification or add additional context in comments.

2 Comments

the main problem with reset approach is that after this you wont be able to completely reset the form, as the object you pass to reset function becomes the default values
I'm not sure i understand your comment correctly, but you can pass a config object to reset. One of the props is keepDefaultValues and prevents overwriting the default values. You can read more about it here.
2

in case the previous form values are also needed:

useEffect(() => {
    if (userData) {
      reset((prev) => ({...prev, ...userData}));
    }
}, [userData, reset]);

Comments

1

first: why do you check for userData, but than use userBillingData?

second: as i dont know what userBillingData is, you can use:

useEffect(() => {
    if (userData) {
      Object.entries(userBillingData).forEach(
        ([name, value]: any) => setValue(name, value));
    }
}, [setValue, userData]);

otherwise you will have to cast the correct type.

ES7 Object.entries() in TypeScript not working

1 Comment

Yeap, sorry userBillingData should be userData.
1

You can use keyof in that case:

useEffect(() => {
    if (userData) {
      Object.entries(userBillingData).forEach(
        ([name, value]) => setValue(name as keyof DataResponse, value));
    }
}, [setValue, userData]);

2 Comments

Still throwing an error
I've successfully did it like this setValue(name as keyof FormData, value);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.