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 |
|
44 | (_a = window.removeEventListener) === null || _a === void 0 ? void 0 : _a.call(window, "storage", syncTabs);
|
45 | const storedState = await storage.getItem(persistKey);
|
46 | if (!storedState) {
|
47 | return;
|
48 | }
|
49 | const stateObject = JSON.parse(storedState);
|
50 | const { dispatch } = store;
|
51 | const mappedState = mapStateToPersist
|
52 | ? mapStateToPersist(stateObject)
|
53 | : stateObject;
|
54 | dispatch({
|
55 | type: persist_1.INITIALIZE_STATE_FROM_STORAGE,
|
56 | payload: mappedState,
|
57 | });
|
58 |
|
59 | (_b = window.addEventListener) === null || _b === void 0 ? void 0 : _b.call(window, "storage", syncTabs);
|
60 | }
|
61 | catch (error) {
|
62 | if (__DEV__) {
|
63 | console.error(error);
|
64 | }
|
65 | }
|
66 | },
|
67 | };
|
68 | return store;
|
69 | };
|
70 |
|
\ | No newline at end of file |