-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontrolled.js
40 lines (34 loc) · 928 Bytes
/
controlled.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
import React, { useCallback, useEffect, useMemo } from 'react'
import { assertNumber } from './utils'
export default function useControlledTokenPagination(
pageNumber,
stateHookFactory = () => React.useState
) {
assertNumber('pageNumber', pageNumber)
const useState = stateHookFactory('controlled')
const [mapping, setMapping] = useState({})
const updateToken = useCallback(
nextToken => {
setMapping(m => ({
...m,
[pageNumber + 1]: nextToken,
}))
},
[pageNumber]
)
const useUpdateToken = useCallback(
function useUpdateToken(nextToken) {
useEffect(() => updateToken(nextToken), [nextToken])
},
[updateToken]
)
return useMemo(
() => ({
currentToken: mapping[pageNumber],
useUpdateToken,
updateToken,
hasToken: pageNumber => pageNumber in mapping,
}),
[mapping, pageNumber, updateToken, useUpdateToken]
)
}