forked from streamich/react-use
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useMap.ts
47 lines (40 loc) · 1.1 KB
/
useMap.ts
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 { useState, useMemo, useCallback } from 'react';
export interface StableActions<T extends object> {
set: <K extends keyof T>(key: K, value: T[K]) => void;
setAll: (newMap: T) => void;
remove: <K extends keyof T>(key: K) => void;
reset: () => void;
}
export interface Actions<T extends object> extends StableActions<T> {
get: <K extends keyof T>(key: K) => T[K];
}
const useMap = <T extends object = any>(initialMap: T = {} as T): [T, Actions<T>] => {
const [map, set] = useState<T>(initialMap);
const stableActions = useMemo<StableActions<T>>(
() => ({
set: (key, entry) => {
set(prevMap => ({
...prevMap,
[key]: entry,
}));
},
setAll: (newMap: T) => {
set(newMap);
},
remove: key => {
set(prevMap => {
const { [key]: omit, ...rest } = prevMap;
return rest as T;
});
},
reset: () => set(initialMap),
}),
[set]
);
const utils = {
get: useCallback(key => map[key], [map]),
...stableActions,
} as Actions<T>;
return [map, utils];
};
export default useMap;