-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
112 lines (101 loc) · 2.99 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { useState, useEffect, useCallback } from "react";
const enqueue = function (job) {
return new Promise((resolve, reject) => {
this.asyncJobs.push({ job: job, resolve: resolve, reject: reject });
this.dequeue();
});
};
const dequeue = function () {
if (this.workingOnPromise) {
return false;
}
const item = this.asyncJobs.shift();
if (!item) {
return false;
}
try {
this.workingOnPromise = true;
(async () => {
const result = await item.job();
this.workingOnPromise = false;
item.resolve(result);
this.dequeue();
})();
} catch (err) {
this.workingOnPromise = false;
item.reject(err);
this.dequeue();
}
return true;
};
let universe = {};
export const useStore = (sliceIdentifier, shouldTriggerRerender = true) => {
const setState = useState(universe[sliceIdentifier].globalState)[1];
const dispatchAsync = useCallback(
(actionIdentifier, payload) => {
const { listners, actions } = universe[sliceIdentifier];
return universe[sliceIdentifier].enqueue(() => {
return new Promise((resolve, reject) => {
(async () => {
try {
const updatedState = await actions[actionIdentifier](
universe[sliceIdentifier].globalState,
payload
);
universe[sliceIdentifier].globalState = updatedState;
for (const listner of listners) {
listner(universe[sliceIdentifier].globalState);
}
resolve();
} catch (error) {
reject(new Error(error.message));
}
})();
});
});
},
[sliceIdentifier]
);
const dispatch = useCallback(
(actionIdentifier, payload) => {
const { listners, actions } = universe[sliceIdentifier];
try {
const updatedState = actions[actionIdentifier](
universe[sliceIdentifier].globalState,
payload
);
universe[sliceIdentifier].globalState = updatedState;
for (const listner of listners) {
listner(universe[sliceIdentifier].globalState);
}
} catch (error) {
throw new Error(error.message);
}
},
[sliceIdentifier]
);
useEffect(() => {
let { listners } = universe[sliceIdentifier];
if (shouldTriggerRerender) {
listners.push(setState);
return () => {
listners = listners.filter((listner) => listner !== setState);
};
}
}, [setState, shouldTriggerRerender, sliceIdentifier]);
return {state: universe[sliceIdentifier].globalState, dispatch: dispatch, dispatchAsync: dispatchAsync};
};
export const initStoreSlice = (sliceIdentifier, actions, initialState) => {
universe[sliceIdentifier] = {
globalState: initialState,
listners: [],
actions: actions,
asyncJobs: [],
workingOnPromise: false,
enqueue: enqueue,
dequeue: dequeue
};
};
export const deleteStoreSlice = (sliceIdentifier) => {
delete universe[sliceIdentifier];
};