Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

infinite-queries.md

266 lines8.7 KB

1---
2id: infinite-queries
3title: Infinite Queries
4---
5​
6Rendering lists that can additively "load more" data onto an existing set of data or "infinite scroll" is also a very common UI pattern. TanStack Query supports a useful version of `useQuery` called `useInfiniteQuery` for querying these types of lists.
7​
8When using `useInfiniteQuery`, you'll notice a few things are different:
9​
10- `data` is now an object containing infinite query data:
11- `data.pages` array containing the fetched pages
12- `data.pageParams` array containing the page params used to fetch the pages
13- The `fetchNextPage` and `fetchPreviousPage` functions are now available (`fetchNextPage` is required)
14- The `initialPageParam` option is now available (and required) to specify the initial page param
15- The `getNextPageParam` and `getPreviousPageParam` options are available for both determining if there is more data to load and the information to fetch it. This information is supplied as an additional parameter in the query function
16- A `hasNextPage` boolean is now available and is `true` if `getNextPageParam` returns a value other than `null` or `undefined`
17- A `hasPreviousPage` boolean is now available and is `true` if `getPreviousPageParam` returns a value other than `null` or `undefined`
18- The `isFetchingNextPage` and `isFetchingPreviousPage` booleans are now available to distinguish between a background refresh state and a loading more state
19​
20> Note: Options `initialData` or `placeholderData` need to conform to the same structure of an object with `data.pages` and `data.pageParams` properties.
21​
22## Example
23​
24Let's assume we have an API that returns pages of `projects` 3 at a time based on a `cursor` index along with a cursor that can be used to fetch the next group of projects:
25​
26```tsx
27fetch('/api/projects?cursor=0')
28// { data: [...], nextCursor: 3}
29fetch('/api/projects?cursor=3')
30// { data: [...], nextCursor: 6}
31fetch('/api/projects?cursor=6')
32// { data: [...], nextCursor: 9}
33fetch('/api/projects?cursor=9')
34// { data: [...] }
35```
36​
37With this information, we can create a "Load More" UI by:
38​
39- Waiting for `useInfiniteQuery` to request the first group of data by default
40- Returning the information for the next query in `getNextPageParam`
41- Calling `fetchNextPage` function
42​
43[//]: # 'Example'
44​
45```tsx
46import { useInfiniteQuery } from '@tanstack/react-query'
47​
48function Projects() {
49 const fetchProjects = async ({ pageParam }) => {
50 const res = await fetch('/api/projects?cursor=' + pageParam)
51 return res.json()
52 }
53​
54 const {
55 data,
56 error,
57 fetchNextPage,
58 hasNextPage,
59 isFetching,
60 isFetchingNextPage,
61 status,
62 } = useInfiniteQuery({
63 queryKey: ['projects'],
64 queryFn: fetchProjects,
65 initialPageParam: 0,
66 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
67 })
68​
69 return status === 'pending' ? (
70 <p>Loading...</p>
71 ) : status === 'error' ? (
72 <p>Error: {error.message}</p>
73 ) : (
74 <>
75 {data.pages.map((group, i) => (
76 <React.Fragment key={i}>
77 {group.data.map((project) => (
78 <p key={project.id}>{project.name}</p>
79 ))}
80 </React.Fragment>
81 ))}
82 <div>
83 <button
84 onClick={() => fetchNextPage()}
85 disabled={!hasNextPage || isFetching}
86 >
87 {isFetchingNextPage
88 ? 'Loading more...'
89 : hasNextPage
90 ? 'Load More'
91 : 'Nothing more to load'}
92 </button>
93 </div>
94 <div>{isFetching && !isFetchingNextPage ? 'Fetching...' : null}</div>
95 </>
96 )
98```
99​
100[//]: # 'Example'
101​
102It's essential to understand that calling `fetchNextPage` while an ongoing fetch is in progress runs the risk of overwriting data refreshes happening in the background. This situation becomes particularly critical when rendering a list and triggering `fetchNextPage` simultaneously.
103​
104Remember, there can only be a single ongoing fetch for an InfiniteQuery. A single cache entry is shared for all pages, attempting to fetch twice simultaneously might lead to data overwrites.
105​
106If you intend to enable simultaneous fetching, you can utilize the `{ cancelRefetch: false }` option (default: true) within `fetchNextPage`.
107​
108To ensure a seamless querying process without conflicts, it's highly recommended to verify that the query is not in an `isFetching` state, especially if the user won't directly control that call.
109​
110[//]: # 'Example1'
111​
112```jsx
113<List onEndReached={() => hasNextPage && !isFetching && fetchNextPage()} />
114```
115​
116[//]: # 'Example1'
117​
118## What happens when an infinite query needs to be refetched?
119​
120When an infinite query becomes `stale` and needs to be refetched, each group is fetched `sequentially`, starting from the first one. This ensures that even if the underlying data is mutated, we're not using stale cursors and potentially getting duplicates or skipping records. If an infinite query's results are ever removed from the queryCache, the pagination restarts at the initial state with only the initial group being requested.
121​
122## What if I want to implement a bi-directional infinite list?
123​
124Bi-directional lists can be implemented by using the `getPreviousPageParam`, `fetchPreviousPage`, `hasPreviousPage` and `isFetchingPreviousPage` properties and functions.
125​
126[//]: # 'Example3'
127​
128```tsx
129useInfiniteQuery({
130 queryKey: ['projects'],
131 queryFn: fetchProjects,
132 initialPageParam: 0,
133 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
134 getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor,
135})
136```
137​
138[//]: # 'Example3'
139​
140## What if I want to show the pages in reversed order?
141​
142Sometimes you may want to show the pages in reversed order. If this is case, you can use the `select` option:
143​
144[//]: # 'Example4'
145​
146```tsx
147useInfiniteQuery({
148 queryKey: ['projects'],
149 queryFn: fetchProjects,
150 select: (data) => ({
151 pages: [...data.pages].reverse(),
152 pageParams: [...data.pageParams].reverse(),
153 }),
154})
155```
156​
157[//]: # 'Example4'
158​
159## What if I want to manually update the infinite query?
160​
161### Manually removing first page:
162​
163[//]: # 'Example5'
164​
165```tsx
166queryClient.setQueryData(['projects'], (data) => ({
167 pages: data.pages.slice(1),
168 pageParams: data.pageParams.slice(1),
169}))
170```
171​
172[//]: # 'Example5'
173​
174### Manually removing a single value from an individual page:
175​
176[//]: # 'Example6'
177​
178```tsx
179const newPagesArray =
180 oldPagesArray?.pages.map((page) =>
181 page.filter((val) => val.id !== updatedId),
182 ) ?? []
183​
184queryClient.setQueryData(['projects'], (data) => ({
185 pages: newPagesArray,
186 pageParams: data.pageParams,
187}))
188```
189​
190[//]: # 'Example6'
191​
192### Keep only the first page:
193​
194[//]: # 'Example7'
195​
196```tsx
197queryClient.setQueryData(['projects'], (data) => ({
198 pages: data.pages.slice(0, 1),
199 pageParams: data.pageParams.slice(0, 1),
200}))
201```
202​
203[//]: # 'Example7'
204​
205Make sure to always keep the same data structure of pages and pageParams!
206​
207## What if I want to limit the number of pages?
208​
209In some use cases you may want to limit the number of pages stored in the query data to improve the performance and UX:
210​
211- when the user can load a large number of pages (memory usage)
212- when you have to refetch an infinite query that contains dozens of pages (network usage: all the pages are sequentially fetched)
213​
214The solution is to use a "Limited Infinite Query". This is made possible by using the `maxPages` option in conjunction with `getNextPageParam` and `getPreviousPageParam` to allow fetching pages when needed in both directions.
215​
216In the following example only 3 pages are kept in the query data pages array. If a refetch is needed, only 3 pages will be refetched sequentially.
217​
218[//]: # 'Example8'
219​
220```tsx
221useInfiniteQuery({
222 queryKey: ['projects'],
223 queryFn: fetchProjects,
224 initialPageParam: 0,
225 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
226 getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor,
227 maxPages: 3,
228})
229```
230​
231[//]: # 'Example8'
232​
233## What if my API doesn't return a cursor?
234​
235If your API doesn't return a cursor, you can use the `pageParam` as a cursor. Because `getNextPageParam` and `getPreviousPageParam` also get the `pageParam`of the current page, you can use it to calculate the next / previous page param.
236​
237[//]: # 'Example9'
238​
239```tsx
240return useInfiniteQuery({
241 queryKey: ['projects'],
242 queryFn: fetchProjects,
243 initialPageParam: 0,
244 getNextPageParam: (lastPage, allPages, lastPageParam) => {
245 if (lastPage.length === 0) {
246 return undefined
247 }
248 return lastPageParam + 1
249 },
250 getPreviousPageParam: (firstPage, allPages, firstPageParam) => {
251 if (firstPageParam <= 1) {
252 return undefined
253 }
254 return firstPageParam - 1
255 },
256})
257```
258​
259[//]: # 'Example9'
260[//]: # 'Materials'
261​
262## Further reading
263​
264To get a better understanding of how Infinite Queries work under the hood, see the article [How Infinite Queries work](https://tkdodo.eu/blog/how-infinite-queries-work).
265​
266[//]: # 'Materials'