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

paginated-queries.md

93 lines3.3 KB

1---
2id: paginated-queries
3title: Paginated / Lagged Queries
4---
5​
6Rendering paginated data is a very common UI pattern and in TanStack Query, it "just works" by including the page information in the query key:
7​
8[//]: # 'Example'
9​
10```tsx
11const result = useQuery({
12 queryKey: ['projects', page],
13 queryFn: fetchProjects,
14})
15```
16​
17[//]: # 'Example'
18​
19However, if you run this simple example, you might notice something strange:
20​
21**The UI jumps in and out of the `success` and `pending` states because each new page is treated like a brand new query.**
22​
23This experience is not optimal and unfortunately is how many tools today insist on working. But not TanStack Query! As you may have guessed, TanStack Query comes with an awesome feature called `placeholderData` that allows us to get around this.
24​
25## Better Paginated Queries with `placeholderData`
26​
27Consider the following example where we would ideally want to increment a pageIndex (or cursor) for a query. If we were to use `useQuery`, **it would still technically work fine**, but the UI would jump in and out of the `success` and `pending` states as different queries are created and destroyed for each page or cursor. By setting `placeholderData` to `(previousData) => previousData` or `keepPreviousData` function exported from TanStack Query, we get a few new things:
28​
29- **The data from the last successful fetch is available while new data is being requested, even though the query key has changed**.
30- When the new data arrives, the previous `data` is seamlessly swapped to show the new data.
31- `isPlaceholderData` is made available to know what data the query is currently providing you
32​
33[//]: # 'Example2'
34​
35```tsx
36import { keepPreviousData, useQuery } from '@tanstack/react-query'
37import React from 'react'
38​
39function Todos() {
40 const [page, setPage] = React.useState(0)
41​
42 const fetchProjects = (page = 0) =>
43 fetch('/api/projects?page=' + page).then((res) => res.json())
44​
45 const { isPending, isError, error, data, isFetching, isPlaceholderData } =
46 useQuery({
47 queryKey: ['projects', page],
48 queryFn: () => fetchProjects(page),
49 placeholderData: keepPreviousData,
50 })
51​
52 return (
53 <div>
54 {isPending ? (
55 <div>Loading...</div>
56 ) : isError ? (
57 <div>Error: {error.message}</div>
58 ) : (
59 <div>
60 {data.projects.map((project) => (
61 <p key={project.id}>{project.name}</p>
62 ))}
63 </div>
64 )}
65 <span>Current Page: {page + 1}</span>
66 <button
67 onClick={() => setPage((old) => Math.max(old - 1, 0))}
68 disabled={page === 0}
69 >
70 Previous Page
71 </button>
72 <button
73 onClick={() => {
74 if (!isPlaceholderData && data.hasMore) {
75 setPage((old) => old + 1)
76 }
77 }}
78 // Disable the Next Page button until we know a next page is available
79 disabled={isPlaceholderData || !data?.hasMore}
80 >
81 Next Page
82 </button>
83 {isFetching ? <span> Loading...</span> : null}
84 </div>
85 )
87```
88​
89[//]: # 'Example2'
90​
91## Lagging Infinite Query results with `placeholderData`
92​
93While not as common, the `placeholderData` option also works flawlessly with the `useInfiniteQuery` hook, so you can seamlessly allow your users to continue to see cached data while infinite query keys change over time.