Bernard Hymmen
Bernard Hymmen

Reputation: 857

How do I keep TanStack useQuery from refetching data when it returns results from its cache?

I have a web site that uses TanStack's useQuery hook to get data and an API to provide that data. Recently, my API hit a breakpoint while I was debugging it. This happened prior to my API returning its response but I noticed that my web site had updated anyway. Apparently TanStack had both provided cached data from a previous request and made a fetch request to the API. The data being served from my API is not rapidly changing or subject to mutations, so working with previously cached results is just fine (ideal, really), but making redundant service call is obviously not great and is something I'd like to avoid.

I am aware of the refetchOnMount and refetchOnWindowFocus flags in the useQuery options and have those both set to false.

Here's a CodePen that demonstrates this behavior: https://codepen.io/BernardHymmen/pen/WNYoXqW

The demo switches back and forth between "lead" and "gold". The first two fetches show the "Loading" message as expected when getting the data for the two metals. On subsequent presses of the "Transmute" button, pay attention to timing between when the data panel updates and when the responseTime updates. Thanks to an artificial two-second delay built into the API call, you'll see that the data switches well before useQuery makes the fetch results available, and if you watch the marker field in the response you will see the original cached value appears first and is eventually overwritten by the response from the fetch.

I'd like to get useQuery to stop making that unnecessary fetch.

Upvotes: 0

Views: 2594

Answers (1)

Bernard Hymmen
Bernard Hymmen

Reputation: 857

When I initially ran into this problem I spent quite a bit of time going through the TanStack documentation in general and useQuery in particular. Of course I came across the staleTime and cacheTime options and tried using those, but they didn't seem to behave as expected. After going through the trouble of putting the CodePen together and creating this question, I decided to check one last time and discovered that I had been setting

staleTime: "Infinity"

rather than

staleTime: Infinity

D'OH! Once I started setting staleTime to an actual value rather than a string things started to work as expected.

Upvotes: 0

Related Questions