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
81 lines (72 loc) · 1.88 KB
/
usePaginatedCollection.js
File metadata and controls
81 lines (72 loc) · 1.88 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
73
74
75
76
77
78
79
80
81
import { useState } from 'react'
import { useQuery } from '@apollo/client'
import { indexes } from './indexes'
export function usePaginatedCollection({
recordsPerPage,
fetchForward,
fetchHeaders = {},
variables,
relayRoot,
...rest
}) {
const [currentPage, setCurrentPage] = useState(1)
const { loading, error, data, fetchMore } = useQuery(fetchForward, {
variables: { first: recordsPerPage, ...variables },
context: {
headers: fetchHeaders,
},
...rest,
})
const [isLoadingMore, setIsLoadingMore] = useState(false)
let currentEdges = []
let currentPageInfo = {}
let totalCount = 0
if (data) {
currentEdges = relayRoot.split('.').reduce((acc, cur) => {
return acc[cur]
}, data)
totalCount = currentEdges?.totalCount || 0
currentPageInfo = currentEdges?.pageInfo
currentEdges = currentEdges?.edges || []
}
const totalPages = Math.ceil(currentEdges.length / recordsPerPage)
if (currentEdges?.length > recordsPerPage) {
currentEdges = currentEdges.slice(
...indexes({
page: currentPage,
recordsPerPage,
}),
)
}
return {
loading,
isLoadingMore,
error,
edges: currentEdges,
nodes: currentEdges?.map((e) => e.node),
totalCount,
setCurrentPage,
next: async () => {
if (currentPage === totalPages) {
setIsLoadingMore(true)
await fetchMore({
variables: {
...variables,
first: recordsPerPage,
after: currentPageInfo.endCursor,
},
})
setIsLoadingMore(false)
}
setCurrentPage(currentPage + 1)
},
previous: () => {
setCurrentPage(currentPage > 2 ? currentPage - 1 : 1)
},
resetToFirstPage: () => {
setCurrentPage(1)
},
hasPreviousPage: currentPage > 1,
hasNextPage: currentPageInfo?.hasNextPage || currentPage < totalPages,
}
}