forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusePaginatedCollection.js
More file actions
72 lines (65 loc) · 1.74 KB
/
usePaginatedCollection.js
File metadata and controls
72 lines (65 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { useState } from 'react'
import { useQuery } from '@apollo/client'
import { setQueryAlias } from './setQueryAlias'
import { indexes } from './indexes'
export function usePaginatedCollection({
recordsPerPage = 10,
fetchForward,
fetchBackward,
fetchHeaders = {},
}) {
const { query: fwdQuery } = setQueryAlias({
query: fetchForward,
alias: 'pagination',
})
const { query: bkwrdQuery } = setQueryAlias({
query: fetchBackward,
alias: 'pagination',
})
const [currentPage, setCurrentPage] = useState(1)
const { loading, error, data, fetchMore } = useQuery(fwdQuery, {
variables: { first: recordsPerPage },
context: {
headers: fetchHeaders,
},
})
let currentEdges
if (data?.pagination?.edges?.length > recordsPerPage) {
currentEdges = data.pagination.edges.slice(
...indexes({
page: currentPage,
recordsPerPage,
}),
)
} else {
currentEdges = data?.pagination?.edges
}
return {
loading,
error,
edges: currentEdges,
nodes: currentEdges?.map((e) => e.node),
next: () => {
setCurrentPage(currentPage + 1)
return fetchMore({
variables: {
first: recordsPerPage,
after:
data && data.pagination ? data.pagination.pageInfo.endCursor : '',
},
})
},
previous: () => {
setCurrentPage(currentPage > 2 ? currentPage - 1 : 1)
return fetchMore({
query: bkwrdQuery,
variables: {
last: recordsPerPage,
before: data ? data.pagination?.pageInfo?.endCursor : '',
},
})
},
hasPreviousPage: data ? data.pagination?.pageInfo?.hasPreviousPage : false,
hasNextPage: data ? data.pagination?.pageInfo?.hasNextPage : false,
}
}