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