-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (44 loc) · 1.19 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 { useMemo, useState } from "react";
class EventEmitter {
eventsMap = {};
addEvent(eventName, callback) {
if (!this.eventsMap[eventName]) this.eventsMap[eventName] = new Set();
this.eventsMap[eventName].add(callback);
return () => {
if (this.eventsMap[eventName]) {
this.eventsMap[eventName].delete(callback);
}
};
}
emit(event) {
if (this.eventsMap[event]) {
(this.eventsMap[event] ?? []).forEach((cb) => {
cb();
});
}
}
}
const createStore = (initialState = {}) => {
const eventEmitter = new EventEmitter();
return (key) => {
const [, reRender] = useState(0);
let removeEvent = null;
// whenever key changes add event for that key
useMemo(() => {
removeEvent = eventEmitter.addEvent(key, () => {
// cause re render when new value added, will emit this later
reRender((prev) => (prev + 1) % Number.MAX_SAFE_INTEGER);
});
}, [key]);
return [
initialState[key],
(cb) => {
initialState[key] = cb(initialState[key]);
// emit event to cause re render
eventEmitter.emit(key);
},
removeEvent,
];
};
};
export default createStore;