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