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

paginated-queries.md

104 lines2.8 KB

1---
2id: paginated-queries
3title: Paginated / Lagged Queries
4ref: docs/framework/react/guides/paginated-queries.md
5replace:
6 {
7 'useQuery': 'injectQuery',
8 'useInfiniteQuery': 'injectInfiniteQuery',
9 'hook': 'function',
10 }
11---
12​
13[//]: # 'Example'
14​
15```ts
16const result = injectQuery(() => ({
17 queryKey: ['projects', page()],
18 queryFn: fetchProjects,
19}))
20```
21​
22[//]: # 'Example'
23[//]: # 'Example2'
24​
25```angular-ts
26@Component({
27 selector: 'pagination-example',
28 template: `
29 <div>
30 <p>
31 In this example, each page of data remains visible as the next page is
32 fetched. The buttons and capability to proceed to the next page are also
33 suppressed until the next page cursor is known. Each page is cached as a
34 normal query too, so when going to previous pages, you'll see them
35 instantaneously while they are also re-fetched invisibly in the
36 background.
37 </p>
38 @if (query.status() === 'pending') {
39 <div>Loading...</div>
40 } @else if (query.status() === 'error') {
41 <div>Error: {{ query.error().message }}</div>
42 } @else {
43 <!-- 'data' will either resolve to the latest page's data -->
44 <!-- or if fetching a new page, the last successful page's data -->
45 <div>
46 @for (project of query.data().projects; track project.id) {
47 <p>{{ project.name }}</p>
48 }
49 </div>
50 }
51​
52 <div>Current Page: {{ page() + 1 }}</div>
53 <button (click)="previousPage()" [disabled]="page() === 0">
54 Previous Page
55 </button>
56 <button
57 (click)="nextPage()"
58 [disabled]="query.isPlaceholderData() || !query.data()?.hasMore"
59 >
60 Next Page
61 </button>
62 <!-- Since the last page's data potentially sticks around between page requests, -->
63 <!-- we can use 'isFetching' to show a background loading -->
64 <!-- indicator since our status === 'pending' state won't be triggered -->
65 @if (query.isFetching()) {
66 <span> Loading...</span>
67 }
68 </div>
69 `,
70})
71export class PaginationExampleComponent {
72 page = signal(0)
73 queryClient = inject(QueryClient)
74​
75 query = injectQuery(() => ({
76 queryKey: ['projects', this.page()],
77 queryFn: () => lastValueFrom(fetchProjects(this.page())),
78 placeholderData: keepPreviousData,
79 staleTime: 5000,
80 }))
81​
82 constructor() {
83 effect(() => {
84 // Prefetch the next page!
85 if (!this.query.isPlaceholderData() && this.query.data()?.hasMore) {
86 this.#queryClient.prefetchQuery({
87 queryKey: ['projects', this.page() + 1],
88 queryFn: () => lastValueFrom(fetchProjects(this.page() + 1)),
89 })
90 }
91 })
92 }
93​
94 previousPage() {
95 this.page.update((old) => Math.max(old - 1, 0))
96 }
97​
98 nextPage() {
99 this.page.update((old) => (this.query.data()?.hasMore ? old + 1 : old))
100 }
102```
103​
104[//]: # 'Example2'