T
TanStack2y ago
absent-sapphire

useInfiniteQuery always refetches when search state changes even if all data has already been fetche

I would like that when a user types in the search bar, we fetch all the results so they are always getting an exhaustive search. So I am passing the columFilters state to the queryKey array. However even if all the results have already been fetched an entire refetch is done when the search key changes. This is not ideal. Can anyone help with a workaround maybe how to prevent refetch when all data has been fetched or better approach? Additionally, when the component unmounts, the query Cache is cleared and it cant be accessed using getQueryData. thanks
No description
No description
4 Replies
metropolitan-bronze
metropolitan-bronze2y ago
please show a minimal, runnable reproduction
absent-sapphire
absent-sapphireOP2y ago
Thank you for taking the time. I have created a minimal reproduction as requested. Please help me check it out at: https://codesandbox.io/p/sandbox/twilight-glade-66rh39?file=%2Fsrc%2Findex.tsx%3A19%2C1
metropolitan-bronze
metropolitan-bronze2y ago
if the key changes, you'll get a new cache entry. You can see that very well when adding the devtools. That cache entry has nothing to do with the previous cache entry, so it starts from scratch. you'd either want your search to be server side (by adding it to the key) or client side (by fetching everything and filtering locally, thus not adding it to the key)
metropolitan-bronze
metropolitan-bronze2y ago
you can set initialData for a cache entry by looking at other cache entries (e.g. when searched for AB, you look at the cache entry for A) and using that as initial data. An example for that is here: https://tanstack.com/query/v5/docs/framework/react/guides/initial-query-data#initial-data-from-cache then, if you have a staleTime set and that data is still fresh, you won't see a refetch.
Initial Query Data | TanStack Query Docs
There are many ways to supply initial data for a query to the cache before you need it: Declaratively:

Did you find this page helpful?