isPending equivalent for queryKey change / bool that distinguishes background refetch from qk change
Hi guys,
Building a UI right now which is fetching data via an API using useInfiniteQuery. I'm swapping parameters in the queryKey to automatically fetch new data via the API when sorting or filtering parameters change. So far so normal.
These fetch operations are super expensive and slow so I have a loading state rendering in the UI when a filter or sort condition is applied. Originally I had this keyed to isFetching but I've noticed that it's blocking the UI when a background refetch is in-flight, which is absolutely not what I want. For various reasons it's not appropriate to configure a high staletime value on the queryCache and background refetches are important to keep data updated. However because the API is slow I can't sacrifice my loading state when a filter or sort condition is applied.
I was pretty confident that I could use isPending instead for queryKey changes but I've noticed that a queryKey parameter switch changes the isFetching and isRefetching boolean state rather than isPending, even though that particular key has never been fetched before.
Is there an out of the box solution to distinguish between background refetches of data that is already in the cache and a new fetch occuring because the queryKey has changed?
4 Replies
stormy-goldOP•2y ago
Super grateful for any input.
typical-coral•2y ago
but I've noticed that a queryKey parameter switch changes the isFetching and isRefetching boolean state rather than isPending, even though that particular key has never been fetched before.if there is no data for a given key,
isPending
will be true. So there must be some other setting you're not telling us about, like placeholderData
or initialData
maybe. Impossible to say without seeing a reproductionstormy-goldOP•2y ago
Thanks @TkDodo 🔮 I'll have a dig into the implementation further.
Ok @TkDodo 🔮 I've isolated the issue. With KeepPreviousData applied the isRefetching flag is active in the case I've noted above rather than the isPending flag - at least in our implementation. Leveraging isPlaceholder || isPending solves my issue. Only question - is that expected behaviour? May be worth a clarification in the isPending documentation entry if so. If not I'll try to reproduce in another environment.
Thanks for your help.
typical-coral•2y ago
keepPreviousData is placeholderData, so yes, it's expected that your query is not pending, because pending means "the query has no data yet", which is documented here: https://tanstack.com/query/latest/docs/framework/react/guides/queries