-
Notifications
You must be signed in to change notification settings - Fork 1
/
import React, { useState, useCallback, u.js
80 lines (71 loc) · 1.97 KB
/
import React, { useState, useCallback, u.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
73
74
75
76
77
78
79
80
import React, { useState, useCallback, useEffect } from 'react';
export const Context = React.createContext();
export function DropdownProvider({ children }) {
const [options, setOptions] = useState([]);
const [targetId, setTargetId] = useState(null);
const [cachedId, setCachedId] = useState(null);
const registerOption = useCallback(
({
id,
optionDimensions,
optionCenterX,
WrappedContent,
backgroundHeight,
}) => {
setOptions((items) => [
...items,
{
id,
optionDimensions,
optionCenterX,
WrappedContent,
backgroundHeight,
},
]);
},
[setOptions]
);
const updateOptionProps = useCallback(
(optionId, props) => {
setOptions((items) =>
items.map((item) => {
if (item.id === optionId) {
item = { ...item, ...props };
}
return item;
})
);
},
[setOptions]
);
const getOptionById = useCallback(
(id) => options.find((item) => item.id === id),
[options]
);
const deleteOptionById = useCallback(
(id) => {
setOptions((items) => items.filter((item) => item.id !== id));
},
[setOptions]
);
useEffect(() => {
if (targetId !== null) setCachedId(targetId);
}, [targetId]);
return (
<Context.Provider
value={{
registerOption,
updateOptionProps,
getOptionById,
deleteOptionById,
options,
targetId,
setTargetId,
cachedId,
setCachedId,
}}
>
{children}
</Context.Provider>
);
}