Jokcy
Jokcy2y ago

Cache not working for `useQuery`

I have a query like this:
const { data: article, isFetching } = api.public.getArticle.useQuery({
id: targetId,
});
const { data: article, isFetching } = api.public.getArticle.useQuery({
id: targetId,
});
which targetId is a dynamic value. When I change targetId from a to b then switch back from b to a, the useQuery hook still send a new request for a instead of using cache. Any idea how to make the cache work?
5 Replies
Nick
Nick2y ago
You can set the stale time and cache time for queries and globally. It’s quite aggressive by default I believe https://tanstack.com/query/v4/docs/react/guides/important-defaults
Important Defaults | TanStack Query Docs
Out of the box, TanStack Query is configured with aggressive but sane defaults. Sometimes these defaults can catch new users off guard or make learning/debugging difficult if they are unknown by the user. Keep them in mind as you continue to learn and use TanStack Query: Query instances via useQuery or useInfiniteQuery by default consider cach...
Nick
Nick2y ago
It’s probably working as intended though
Jokcy
JokcyOP2y ago
Actually I did, I set cacheTime: Infinity it still not work. Note useQuery should have default cacheTime which is 5m so my code should work with cache by default.
Nick
Nick2y ago
And stale time?
Jokcy
JokcyOP2y ago
Yeah, sorry did not notic the stale time, work now THX.