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

index.tsx

121 lines3.1 KB

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