1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.createStore = void 0;
|
4 | const react_1 = require("react");
|
5 | const observe_1 = require("./observe");
|
6 | const persist_1 = require("./persist");
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | exports.createStore = ({ reducer, initialState, mapStateToPersist, storage = window.localStorage, persistKey, }) => {
|
12 | const stateContext = observe_1.createObserveContext(initialState);
|
13 | const dispatchContext = react_1.createContext(() => { });
|
14 | function syncTabs(event) {
|
15 | const { dispatch } = store;
|
16 | if (event.key === persistKey && event.newValue !== event.oldValue) {
|
17 | dispatch({
|
18 | type: persist_1.INITIALIZE_STATE_FROM_STORAGE,
|
19 | payload: event.newValue ? JSON.parse(event.newValue) : event.newValue,
|
20 | });
|
21 | }
|
22 | }
|
23 | const store = {
|
24 | persistKey,
|
25 | dispatch: () => { },
|
26 | state: initialState,
|
27 | stateContext,
|
28 | dispatchContext,
|
29 | reducer,
|
30 | initialState,
|
31 | useState: (nextObserveState) => {
|
32 | return observe_1.useObserveContext(stateContext, nextObserveState);
|
33 | },
|
34 | useDispatch: () => react_1.useContext(dispatchContext),
|
35 | persist(state, action) {
|
36 | if (action.type !== persist_1.INITIALIZE_STATE_FROM_STORAGE) {
|
37 | storage.setItem(persistKey, JSON.stringify(mapStateToPersist ? mapStateToPersist(state) : state));
|
38 | }
|
39 | },
|
40 | async setToState() {
|
41 | var _a, _b;
|
42 | try {
|
43 | const storedState = await storage.getItem(persistKey);
|
44 | if (!storedState) {
|
45 | return;
|
46 | }
|
47 | const stateObject = JSON.parse(storedState);
|
48 | const { dispatch } = store;
|
49 | const mappedState = mapStateToPersist
|
50 | ? mapStateToPersist(stateObject)
|
51 | : stateObject;
|
52 | dispatch({
|
53 | type: persist_1.INITIALIZE_STATE_FROM_STORAGE,
|
54 | payload: mappedState,
|
55 | });
|
56 | if (persistKey) {
|
57 |
|
58 | (_a = window.removeEventListener) === null || _a === void 0 ? void 0 : _a.call(window, "storage", syncTabs);
|
59 |
|
60 | (_b = window.addEventListener) === null || _b === void 0 ? void 0 : _b.call(window, "storage", syncTabs);
|
61 | }
|
62 | }
|
63 | catch (error) {
|
64 | if (__DEV__) {
|
65 | console.error(error);
|
66 | }
|
67 | }
|
68 | },
|
69 | };
|
70 | return store;
|
71 | };
|
72 |
|
\ | No newline at end of file |