-
-
Notifications
You must be signed in to change notification settings - Fork 491
Expand file tree
/
Copy pathuseCache.ts
More file actions
47 lines (38 loc) · 1.35 KB
/
useCache.ts
File metadata and controls
47 lines (38 loc) · 1.35 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
import * as React from 'react';
import type { RawValueType } from '../BaseSelect';
import type { DefaultOptionType, LabelInValueType } from '../Select';
/**
* Cache `options` related LabeledValue & options.
*/
export default (
labeledValues: LabelInValueType[],
valueOptions: Map<RawValueType, DefaultOptionType>,
): [LabelInValueType[], (val: RawValueType) => DefaultOptionType] => {
const cacheRef = React.useRef({
options: new Map<RawValueType, DefaultOptionType>(),
});
const filledLabeledValues = React.useMemo(() => {
const { options: prevOptionCache } = cacheRef.current;
// Fill label by cache
const patchedValues = labeledValues.map((item) => {
if (item.label === undefined) {
return {
...item,
label: prevOptionCache.get(item.value)?.label,
};
}
return item;
});
const optionCache = new Map<RawValueType, DefaultOptionType>();
patchedValues.forEach((item) => {
optionCache.set(item.value, valueOptions.get(item.value) || prevOptionCache.get(item.value));
});
cacheRef.current.options = optionCache;
return patchedValues;
}, [labeledValues, valueOptions]);
const getOption = React.useCallback(
(val: RawValueType) => valueOptions.get(val) || cacheRef.current.options.get(val),
[valueOptions],
);
return [filledLabeledValues, getOption];
};