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

index.js

119 lines3.0 KB

1import React from 'react'
2import Link from 'next/link'
3import axios from 'axios'
4​
5import { useInfiniteQuery, QueryClient, QueryClientProvider } from 'react-query'
6import { ReactQueryDevtools } from 'react-query/devtools'
7​
8//
9​
10import useIntersectionObserver from '../hooks/useIntersectionObserver'
11​
12const queryClient = new QueryClient()
13​
14export default function App() {
15 return (
16 <QueryClientProvider client={queryClient}>
17 <Example />
18 </QueryClientProvider>
19 )
21​
22function Example() {
23 const {
24 status,
25 data,
26 error,
27 isFetching,
28 isFetchingNextPage,
29 isFetchingPreviousPage,
30 fetchNextPage,
31 fetchPreviousPage,
32 hasNextPage,
33 hasPreviousPage,
34 } = useInfiniteQuery(
35 'projects',
36 async ({ pageParam = 0 }) => {
37 const res = await axios.get('/api/projects?cursor=' + pageParam)
38 return res.data
39 },
40 {
41 getPreviousPageParam: firstPage => firstPage.previousId ?? false,
42 getNextPageParam: lastPage => lastPage.nextId ?? false,
43 }
44 )
45​
46 const loadMoreButtonRef = React.useRef()
47​
48 useIntersectionObserver({
49 target: loadMoreButtonRef,
50 onIntersect: fetchNextPage,
51 enabled: hasNextPage,
52 })
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 {isFetchingNextPage
69 ? 'Loading more...'
70 : hasNextPage
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={loadMoreButtonRef}
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 )