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

infinite-queries.md

201 lines6.9 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
14- 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 (which can optionally be overridden when calling the `fetchNextPage` or `fetchPreviousPage` functions)
15- A `hasNextPage` boolean is now available and is `true` if `getNextPageParam` returns a value other than `undefined`
16- A `hasPreviousPage` boolean is now available and is `true` if `getPreviousPageParam` returns a value other than `undefined`
17- The `isFetchingNextPage` and `isFetchingPreviousPage` booleans are now available to distinguish between a background refresh state and a loading more state
18​
19> Note: When using options like `initialData` or `select` in your query, make sure that when you restructure your data that it still includes `data.pages` and `data.pageParams` properties, otherwise your changes will be overwritten by the query in its return!
20​
21## Example
22​
23Let'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:
24​
25```tsx
26fetch('/api/projects?cursor=0')
27// { data: [...], nextCursor: 3}
28fetch('/api/projects?cursor=3')
29// { data: [...], nextCursor: 6}
30fetch('/api/projects?cursor=6')
31// { data: [...], nextCursor: 9}
32fetch('/api/projects?cursor=9')
33// { data: [...] }
34```
35​
36With this information, we can create a "Load More" UI by:
37​
38- Waiting for `useInfiniteQuery` to request the first group of data by default
39- Returning the information for the next query in `getNextPageParam`
40- Calling `fetchNextPage` function
41​
42> Note: It's very important you do not call `fetchNextPage` with arguments unless you want them to override the `pageParam` data returned from the `getNextPageParam` function. e.g. Do not do this: `<button onClick={fetchNextPage} />` as this would send the onClick event to the `fetchNextPage` function.
43​
44[//]: # 'Example'
45​
46```tsx
47import { useInfiniteQuery } from '@tanstack/react-query'
48​
49function Projects() {
50 const fetchProjects = async ({ pageParam = 0 }) => {
51 const res = await fetch('/api/projects?cursor=' + pageParam)
52 return res.json()
53 }
54​
55 const {
56 data,
57 error,
58 fetchNextPage,
59 hasNextPage,
60 isFetching,
61 isFetchingNextPage,
62 status,
63 } = useInfiniteQuery({
64 queryKey: ['projects'],
65 queryFn: fetchProjects,
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.projects.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 || isFetchingNextPage}
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​
102## What happens when an infinite query needs to be refetched?
103​
104When 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.
105​
106## What if I want to implement a bi-directional infinite list?
107​
108Bi-directional lists can be implemented by using the `getPreviousPageParam`, `fetchPreviousPage`, `hasPreviousPage` and `isFetchingPreviousPage` properties and functions.
109​
110[//]: # 'Example3'
111​
112```tsx
113useInfiniteQuery({
114 queryKey: ['projects'],
115 queryFn: fetchProjects,
116 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
117 getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor,
118})
119```
120​
121[//]: # 'Example3'
122​
123## What if I want to show the pages in reversed order?
124​
125Sometimes you may want to show the pages in reversed order. If this is case, you can use the `select` option:
126​
127[//]: # 'Example4'
128​
129```tsx
130useInfiniteQuery({
131 queryKey: ['projects'],
132 queryFn: fetchProjects,
133 select: (data) => ({
134 pages: [...data.pages].reverse(),
135 pageParams: [...data.pageParams].reverse(),
136 }),
137})
138```
139​
140[//]: # 'Example4'
141​
142## What if I want to manually update the infinite query?
143​
144Manually removing first page:
145​
146[//]: # 'Example5'
147​
148```tsx
149queryClient.setQueryData(['projects'], (data) => ({
150 pages: data.pages.slice(1),
151 pageParams: data.pageParams.slice(1),
152}))
153```
154​
155[//]: # 'Example5'
156​
157Manually removing a single value from an individual page:
158​
159[//]: # 'Example6'
160​
161```tsx
162const newPagesArray =
163 oldPagesArray?.pages.map((page) =>
164 page.filter((val) => val.id !== updatedId),
165 ) ?? []
166​
167queryClient.setQueryData(['projects'], (data) => ({
168 pages: newPagesArray,
169 pageParams: data.pageParams,
170}))
171```
172​
173[//]: # 'Example6'
174​
175Make sure to keep the same data structure of pages and pageParams!
176​
177[//]: # 'Example7'
178​
179## What if I want to limit the number of pages?
180​
181In some use cases you may want to limit the number of pages stored in the query data to improve the performance and UX:
182​
183- when the user can load a large number of pages (memory usage)
184- when you have to refetch an infinite query that contains dozens of pages (network usage: all the pages are sequentially fetched)
185​
186The solution is to use an "Eternal Query": a scalable infinite query.
187This is made possible by using the `maxPages` option in conjunction with `getNextPageParam` and `getPreviousPageParam` to allow fetching pages when needed in both directions.
188​
189In 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.
190​
191[//]: # 'Example7'
192​
193```tsx
194useInfiniteQuery({
195 queryKey: ['projects'],
196 queryFn: fetchProjects,
197 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
198 getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor,
199 maxPages: 3,
200})
201```