Make .useInfiniteQuery global

I have an infinite query and 2 different places where I want to have the data/fetch new data. These are my considerations: 1. I can't pass the data via a simple child component (lifting state up) because the other place is a page created via dynamic routes ([id].tsx) 2. I can't make the .useInfiniteQuery reside outside of a component, so I can't really share data via exporting 3. I tried using zustand/jotai to make the data and the fetchNextPage() global. This works as far as getting the first page of data and also running another db query for the second page, but fails when I want to get the data of the second page. (which means I really haven't found a way to get data from this point on)
12 Replies
Neto
Neto3y ago
you can use a common key for react-query
Johnson
JohnsonOP3y ago
Query Keys | TanStack Query Docs
At its core, React Query manages query caching for you based on query keys. Query keys have to be an Array at the top level, and can be as simple as an Array with a single string, or as complex as an array of many strings and nested objects. As long as the query key is serializable, and unique to the query's data, you can use it! Simple Query ...
Neto
Neto3y ago
yes use the same key between the useQuery calls
Neto
Neto3y ago
"The unique key you provide is used internally for refetching, caching, and sharing your queries throughout your application." https://tanstack.com/query/v4/docs/guides/queries
Queries | TanStack Query Docs
Query Basics A query is a declarative dependency on an asynchronous source of data that is tied to a unique key. A query can be used with any Promise based method (including GET and POST methods) to fetch data from a server. If your method modifies data on the server, we recommend using Mutations instead.
Johnson
JohnsonOP3y ago
ahh so I basically define the .useInfiniteQuery in 2 places. But because I give them the same queryKey, they 'work together' just as if it was one query did I understand that correctly?
Neto
Neto3y ago
if you use useQuery(['some-common-key'], fetcher) in two places it will keep it at sync
Johnson
JohnsonOP3y ago
yeah
Neto
Neto3y ago
in both places
Johnson
JohnsonOP3y ago
nice
Neto
Neto3y ago
if one change, the other will too
Johnson
JohnsonOP3y ago
alright, I will try that, ty!
cje
cje3y ago
in addition to the point that two queries with the same querykey are actually the same query, you can create a custom hook that has the query + any options it needs inside of it
Want results from more Discord servers?
Add your server