UNPKG

2.78 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.createStore = void 0;
4const react_1 = require("react");
5const observe_1 = require("./observe");
6const persist_1 = require("./persist");
7/**
8 * This function give you an store, use that in your components which want to
9 * connect to store and provider
10 */
11exports.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 /** Listening to previously added event */
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 /** Listening to events between tabs */
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//# sourceMappingURL=createStore.js.map
\No newline at end of file