Home > Software design >  How to retype response from API using useQuery?
How to retype response from API using useQuery?

Time:11-10

So Im using useQuery from react-query I need to return response from API as a User (based on my interface).

I did it like this:

export const getUsersQuery = () => "users";

export const useUsersQuery = () =>
 useQuery(getUsersQueryKey(), () =>
   axios
      .get("API ENDPOINT")
      .then((response) => response.data as User[])
);

My friend told me that this is not wrong but its also not "best practice" and that I should look up how to retype my response without the response.data as User[] using generic parameters of useQuery and pass the array of Users as one of the parameters.

Can somebody walk me through how to change my code?

CodePudding user response:

Your friend is partly right, you can actually provide generic type to useQuery function like this

useQuery<User[]>(key, queryFn);

BUT the best way to do this is to simply add the response type to your queryFunction (the second param of useQuery). If you specifically write what it returns, the return type of useQuery will be correct, no need to provide generic type. You can read about it here

CodePudding user response:

Right after I post this I found an answer. As Marat said, the generic function could look like this useQuery<User[]>(key, queryFn);. I found this blog which helped me to understand generics of useQuery better.

React Query heavily uses Generics. This is necessary because the library does not actually fetch data for you, and it cannot know what type the data will have that your api returns.

After chaning my code, the result looks like this:

export const getUsersQuery = () => "users";

export const useUsersQuery = () =>
 useQuery<User[], Error>(getUsersQueryKey(), () =>
   axios
      .get("API ENDPOINT")
      .then((response) => response.data)
);

Hope this helps someone in the future.

  • Related