Home > Blockchain >  How to set multiple values at once in react hook form using Typescript
How to set multiple values at once in react hook form using Typescript

Time:12-08

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"

CodePudding user response:

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

CodePudding user response:

You can use keyof in that case:

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