-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (43 loc) · 1.12 KB
/
index.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
import { useEffect, useState } from "react";
const store = {};
let cnt = 0;
const addGlobalStateEntry = (key, defaultValue) => {
while (typeof defaultValue === "function") {
defaultValue = defaultValue();
}
store[key] = {
setState: (val) => setGlobalState(key, val),
listeners: new Set(),
state: defaultValue,
};
};
export const setGlobalState = (key, val, dontEmit = false) => {
if (key in store) {
if (store[key].state !== val) {
store[key].state = val;
if (!dontEmit) {
cnt++;
store[key].listeners.forEach((fn) => fn(cnt));
}
}
} else {
addGlobalStateEntry(key, val);
}
};
export const getGlobalState = (key) => {
return (key in store && store[key].state) || undefined;
};
const useGlobalState = (key, defaultValue) => {
if (!(key in store)) {
addGlobalStateEntry(key, defaultValue);
}
useEffect(() => {
return () => {
store[key].listeners.delete(setState);
};
}, [key]);
const [, setState] = useState(cnt);
store[key].listeners.add(setState);
return [store[key].state, store[key].setState];
};
export default useGlobalState;