React Query - staleTime and cached value

664 Views Asked by At

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;
        },
      },
    ],
  });

startingPoint

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

1

There are 1 best solutions below

0
TkDodo On

This is what staleTime is for, and setting it to Infinity works for me. Here's a fork of your reproduction:

Note that it's also important to move the queryClient out of the App component to make it stable. Otherwise, your cache will be removed in case your App re-renders.