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

index.js

77 lines1.7 KB

1import React from 'react'
2import fetch from '../libs/fetch'
3import Link from 'next/link'
4​
5import { useQuery } from 'react-query'
6​
7export default () => {
8 const {
9 data,
10 isLoading,
11 isFetching,
12 isFetchingMore,
13 fetchMore,
14 canFetchMore,
15 } = useQuery(
16 'projects',
17 ({ nextId } = {}) => fetch('/api/projects?cursor=' + (nextId || 0)),
18 {
19 paginated: true,
20 getCanFetchMore: lastPage => lastPage.nextId,
21 }
22 )
23​
24 const loadMore = async () => {
25 try {
26 const { nextId } = data[data.length - 1]
27​
28 await fetchMore({
29 nextId,
30 })
31 } catch {}
32 }
33​
34 return (
35 <div>
36 <h1>Pagination</h1>
37 {isLoading ? (
38 <p>Loading...</p>
39 ) : data ? (
40 <>
41 {data.map((page, i) => (
42 <React.Fragment key={i}>
43 {page.data.map(project => (
44 <p
45 style={{
46 border: '1px solid gray',
47 borderRadius: '5px',
48 padding: '5rem 1rem',
49 }}
50 key={project.id}
51 >
52 {project.name}
53 </p>
54 ))}
55 </React.Fragment>
56 ))}
57 <div>
58 {canFetchMore ? (
59 <button onClick={loadMore} disabled={isFetchingMore}>
60 {isFetchingMore ? 'Loading more...' : 'Load More'}
61 </button>
62 ) : (
63 'Nothing more to fetch.'
64 )}
65 </div>
66 <div>
67 {isFetching && !isFetchingMore ? 'Background Updating...' : null}
68 </div>
69 </>
70 ) : null}
71 <hr />
72 <Link href="/about">
73 <a>Go to another page</a>
74 </Link>
75 </div>
76 )