-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuncontrolled.js
72 lines (58 loc) · 1.91 KB
/
uncontrolled.js
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 React, { useCallback, useMemo } from 'react'
import useControlledTokenPagination from './controlled'
import { assertNumber } from './utils'
const DEFAULTS = {
defaultPageNumber: 1,
resetPageNumberOnPageSizeChange: true,
}
const changerTypes = ['function', 'number']
export default function useUncontrolledTokenPagination(
options,
stateHookFactory = () => React.useState
) {
options = { ...DEFAULTS, ...options }
assertNumber('defaultPageNumber', options.defaultPageNumber)
assertNumber('defaultPageSize', options.defaultPageSize)
const useState = stateHookFactory('uncontrolled')
const [{ pageNumber, pageSize }, setPagination] = useState({
pageNumber: options.defaultPageNumber,
pageSize: options.defaultPageSize,
})
const change = useCallback(
(property, changer) => {
const pageNumberReset = options.resetPageNumberOnPageSizeChange
? { pageNumber: options.defaultPageNumber }
: null
const changerType = typeof changer
if (!changerTypes.includes(changerType)) {
throw new Error(
`Unsupported value ${changer} of type ${changerType} for ${property}. Supported values are ${changerTypes}`
)
}
setPagination(p => ({
...p,
...pageNumberReset,
[property]: changerType === 'function' ? changer(p[property]) : changer,
}))
},
[options.defaultPageNumber, options.resetPageNumberOnPageSizeChange]
)
const changePageNumber = useCallback(
changer => change('pageNumber', changer),
[change]
)
const changePageSize = useCallback(changer => change('pageSize', changer), [
change,
])
const controlled = useControlledTokenPagination(pageNumber, stateHookFactory)
return useMemo(
() => ({
...controlled,
pageNumber,
pageSize,
changePageNumber,
changePageSize,
}),
[changePageNumber, changePageSize, pageNumber, pageSize, controlled]
)
}