james emanon
james emanon

Reputation: 11807

My useQuery hook is refetching everytime its called. I thought it is suppose to hand back the cache?

I'm a little confused here. I thought react-query, when using useQuery will hand back 'cache' n subsequent calls to the same "useQuery". But everytime I call it it, it refetches and makes the network call.

Is this the "proper way" to do this? I figured it would just auto hand me the "cache" versions. I tried extending staleTime and cacheTime, neither worked. Always made a network call. I also tried initialData with the cache there.. didn't work.

SO, I am doing the following, but seems dirty.

Here is the what I have for the hook:

export default function useProducts ({
 queryKey="someDefaultKey", id
}){
  const queryClient = useQueryClient();

  return useQuery(
    [queryKey, id],
    async () => {
      const cachedData = await queryClient.getQueryData([queryKey, id]);

      if (cachedData) return cachedData;

      return await products.getOne({ id })
    }, {
        enabled: !!id
       }
  );
}

This is initiated like so:

  const { refetch, data } = useProducts(
      {
        id
      }
    }
  );

I call "refetch" with an onclick in two diff locations.. I'd assume after I retrieve the data.. then subsequent clicks will hand back cache?

Upvotes: 4

Views: 9525

Answers (1)

TkDodo
TkDodo

Reputation: 28833

I’m afraid there are multiple misconceptions here:

  • react query operates on stale-while-revalidate, so it will give you data from the cache and then refetch in the background. You can customize this behavior by setting staleTime, which will tell the library how long the data can be considered fresh. No background updates will happen.
  • when you call refetch, it will refetch. It’s an imperative action. If you don’t want it, don’t call refetch.
  • you don’t need to manually read from the cache in the queryFn - the library will do that for you.

Upvotes: 5

Related Questions