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!
From the docs:
In your setup the query key isn't unique to the data and that's why you get unexpected behavior.
TanStack Query uses the
queryKeyto 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
useGetUserStoriesthequeryKeylooks good. ForuseFetchFeedStoriesa betterqueryKeywould be e.g.['story', 'feed', userId, page]to capture all the "variables".On another note, the way you are using
useInfiniteQueryyou might as well replace it withuseQuery. To make use ofuseInfiniteQueryyou need to provide thegetNextPageParamfunction and accept an input toqueryFn.