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