Open History to see the last commit
1import React from 'react'
2import {
3 QueryClient,
4 QueryClientProvider,
5 useInfiniteQuery,
6} from '@tanstack/react-query'
7import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
8β
9const queryClient = new QueryClient()
10β
11export default function App() {
12 return (
13 <QueryClientProvider client={queryClient}>
14 <Example />
15 </QueryClientProvider>
16 )
17}
18β
19function Example() {
20 const {
21 status,
22 data,
23 error,
24 isFetching,
25 isFetchingNextPage,
26 isFetchingPreviousPage,
27 fetchNextPage,
28 fetchPreviousPage,
29 hasNextPage,
30 hasPreviousPage,
31 } = useInfiniteQuery({
32 queryKey: ['projects'],
33 queryFn: async ({ pageParam }) => {
34 const response = await fetch(`/api/projects?cursor=${pageParam}`)
35 return await response.json()
36 },
37 initialPageParam: 0,
38 getPreviousPageParam: (firstPage) => firstPage.previousId ?? undefined,
39 getNextPageParam: (lastPage) => lastPage.nextId ?? undefined,
40 maxPages: 3,
41 })
42β
43 return (
44 <div>
45 <h1>Infinite Query with max pages</h1>
46 <h3>4 projects per page</h3>
47 <h3>3 pages max</h3>
48 {status === 'pending' ? (
49 <p>Loading...</p>
50 ) : status === 'error' ? (
51 <span>Error: {error.message}</span>
52 ) : (
53 <>
54 <div>
55 <button
56 onClick={() => fetchPreviousPage()}
57 disabled={!hasPreviousPage || isFetchingPreviousPage}
58 >
59 {isFetchingPreviousPage
60 ? 'Loading more...'
61 : hasPreviousPage
62 ? 'Load Older'
63 : 'Nothing more to load'}
64 </button>
65 </div>
66 {data.pages.map((page) => (
67 <React.Fragment key={page.nextId}>
68 {page.data.map((project) => (
69 <p
70 style={{
71 border: '1px solid gray',
72 borderRadius: '5px',
73 padding: '8px',
74 fontSize: '14px',
75 background: `hsla(${project.id * 30}, 60%, 80%, 1)`,
76 }}
77 key={project.id}
78 >
79 {project.name}
80 </p>
81 ))}
82 </React.Fragment>
83 ))}
84 <div>
85 <button
86 onClick={() => fetchNextPage()}
87 disabled={!hasNextPage || isFetchingNextPage}
88 >
89 {isFetchingNextPage
90 ? 'Loading more...'
91 : hasNextPage
92 ? 'Load Newer'
93 : 'Nothing more to load'}
94 </button>
95 </div>
96 <div>
97 {isFetching && !isFetchingNextPage
98 ? 'Background Updating...'
99 : null}
100 </div>
101 </>
102 )}
103 <hr />
104 <ReactQueryDevtools initialIsOpen />
105 </div>
106 )
107}