-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathindex.ts
More file actions
41 lines (31 loc) · 833 Bytes
/
index.ts
File metadata and controls
41 lines (31 loc) · 833 Bytes
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
import {useRef} from 'react';
import {useRerender} from '../useRerender/index.js';
const proto = Map.prototype;
/**
* Tracks the state of a `Map`.
*
* @param entries Initial entries iterator for underlying `Map` constructor.
*/
export function useMap<K = any, V = any>(entries?: ReadonlyArray<readonly [K, V]> | null): Map<K, V> {
const mapRef = useRef<Map<K, V>>(undefined);
const rerender = useRerender();
if (!mapRef.current) {
const map = new Map<K, V>(entries);
mapRef.current = map;
map.set = (...args) => {
proto.set.apply(map, args);
rerender();
return map;
};
map.clear = (...args) => {
proto.clear.apply(map, args);
rerender();
};
map.delete = (...args) => {
const existed = proto.delete.apply(map, args);
rerender();
return existed;
};
}
return mapRef.current;
}