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

index.js

115 lines2.9 KB

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