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

index.js

116 lines3.0 KB

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