Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
like image 449
DragoJokera Avatar asked Sep 05 '25 03:09

DragoJokera


1 Answers

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

useEffect(() => {
    if (userData) {
      reset(userData);
    }
}, [userData, reset]);
like image 178
knoefel Avatar answered Sep 07 '25 19:09

knoefel