r/reactjs • u/the_good_dev • 29d ago
Needs Help Catching problem with react query
Hey I am using tanstack react query I have one component which has
const { data, isPending, isFetching, refetch, isError } = useQuery({
queryKey: ["get"],
queryFn: () => axios.get("http://localhost:3000/"),
staleTime: 60 * 1000
})
On pressing a button i render component 2 with same query key within the catching time with query as
const { data, isPending, isFetching, refetch, isError } = useQuery({
queryKey: ["get"],
queryFn: () => axios.get("http://localhost:3000/"),
// no stale time here
})
Ideally it should not request the backend but it is requesting server
View all comments
3
u/maksymkoval 29d ago
This is expected: staleTime belongs to each useQuery call, not to the cached data. The cache is shared by key, but every component decides on its own whether that data is stale.
Component 2 has no staleTime, so it uses the default of 0. For that component the cached data is already stale, and with refetchOnMount: true (also the default) it refetches in the background when it mounts. You should still see the cached data right away (isPending is false), with isFetching true while the request runs.
Two ways to fix it:
const getQuery = queryOptions({
queryKey: ["get"],
queryFn: () => axios.get("http://localhost:3000/"),
staleTime: 60 * 1000,
})
useQuery(getQuery)
2. Or set a default for the whole app:
new QueryClient({ defaultOptions: { queries: { staleTime: 60 * 1000 } },})
Option 1 is nicer anyway because the key and the fetcher live in one place.