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

index.js

108 lines2.8 KB

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