I was trying to implement react query into one of the projects at work, but I'm struggling with understand staleTime functionality and dynamic queryKeys.
I want to fetch data for specific Producer or Category with dynamic queryKey, but if I set staleTime to Infinity than nothing changes, and if staleTime is 0 than data is fetching everytime.
const [categories, producers] = useQueries({
queries: [
{
queryKey: ["categories", { id: currentProducer }],
queryFn: handleFetchCategories,
// staleTime: Infinity,
refetchOnMount: true,
refetchOnWindowFocus: false,
initialData: currentCategoriesRef.current,
onSuccess: (data: any) => {
currentCategoriesRef.current = data;
},
},
{
queryKey: ["producers", { id: currentCategory }],
queryFn: handleFetchProducers,
// staleTime: Infinity,
refetchOnMount: true,
refetchOnWindowFocus: false,
initialData: currentProducersRef.current,
onSuccess: (data: any) => {
currentProducersRef.current = data;
},
},
],
});
If producer changes then categories for this producer is fetching from the fake backend, and if category is changed the same is happening but with producers
I have created a repo on GitHub that shows specific issue https://github.com/bartokrol/react-query-issue
Do you see how this could be fixed? I want to get cached value (not fetching again) if the specific queryKey has been fetched earilier.
Also if you see something that can be changed also please let me know

This is what
staleTimeis for, and setting it toInfinityworks for me. Here's a fork of your reproduction:Note that it's also important to move the
queryClientout of theAppcomponent to make it stable. Otherwise, your cache will be removed in case yourAppre-renders.