Issue
I have these two custom hooks to execute queries. When the two functions have the same query keys, the second function is blocked and will not be executed. When I remove the userId both queries will be executed. Well for now it's ok for me to remove the userId from the keys, but I just don't unterstand the problem here.
export const useGetUserStories = (userId?: string | null) => {
return useQuery({
queryKey: ['story', userId],
queryFn: async () => {
const stories = await axios.get(`${API_URL}/story/${userId}`);
return stories.data;
},
enabled: !!userId,
});
};
export const useFetchFeedStories = (userId?: string, page?: number) => {
return useInfiniteQuery({
queryKey: ['story', userId],
queryFn: async () => {
const stories = await axios.get(
`${API_URL}/story/feed/${userId}/${page}`
);
return stories.data;
},
enabled: !!userId,
});
};
Any help or different approach is appreciated!
Solution
As long as the query key is serializable, and unique to the query's data, you can use it!
In your setup the query key isn't unique to the data and that's why you get unexpected behavior.
TanStack Query uses the queryKey
to distinguish between various queries. If the query key is identical, TanStack Query will consider them the same and since they are the same it would be redundant to fetch both. So only one is fetched and the data received is provided for both hooks.
To solve this you need to use different query keys for the two queries. For useGetUserStories
the queryKey
looks good. For useFetchFeedStories
a better queryKey
would be e.g. ['story', 'feed', userId, page]
to capture all the "variables".
On another note, the way you are using useInfiniteQuery
you might as well replace it with useQuery
. To make use of useInfiniteQuery
you need to provide the getNextPageParam
function and accept an input to queryFn
.
Answered By - Anton
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.