-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.js
41 lines (36 loc) · 1.11 KB
/
store.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
import { useMemo } from "react";
import { createStore, applyMiddleware } from "redux";
import createSagaMiddleware from "redux-saga";
import { composeWithDevTools } from "redux-devtools-extension";
import rootReducer from "./redux/reducers";
import { watchAuth } from "./redux/sagas";
const sagaMiddleware = createSagaMiddleware();
export function initStore(initialState = {}) {
const Store = createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware(sagaMiddleware))
);
sagaMiddleware.run(watchAuth);
return Store;
}
let store;
export const initializeStore = initialState => {
let _store = store ?? initStore(initialState);
if (initialState && store) {
_store = initStore({
...store.getState(),
...initialState,
});
store = undefined;
}
// For SSG and SSR always create a new store
if (typeof window === "undefined") return _store;
// Create the store once in the client
if (!store) store = _store;
return _store;
};
export function useStore(initialState) {
const store = useMemo(() => initializeStore(initialState), [initialState]);
return store;
}