Issue
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?
Solution
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
Answered By - Marat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.