-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.ts
105 lines (91 loc) · 2.4 KB
/
store.ts
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
import { useMemo } from "react";
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
let store;
export const initialState: InitialState = {
currentLesson: 0,
currentWorld: 0,
lessons: [],
worlds: [],
exercises: [],
isLastWorld: false,
isLastLesson: false,
};
type InitialState = {
currentWorld: number;
currentLesson: number;
lessons: number[];
worlds: number[];
exercises: number[];
isLastWorld: boolean;
isLastLesson: boolean;
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case "SET_WORLD":
const isLastWorld =
action.world === state.worlds[state.worlds.length - 1];
return {
...state,
currentWorld: action.world,
isLastWorld,
};
case "SET_LESSON":
const isLastLesson =
action.lesson === state.lessons[state.lessons.length - 1];
return {
...state,
currentLesson: action.lesson,
isLastLesson,
};
case "SET_LESSONS":
return {
...state,
lessons: action.lessons,
};
case "SET_WORLDS":
return {
...state,
worlds: action.worlds,
};
default:
return state;
}
};
const persistConfig = {
key: "primary",
storage,
whitelist: Object.keys(initialState),
};
const persistedReducer = persistReducer(persistConfig, reducer);
function makeStore(initState = initialState as any) {
return createStore(
persistedReducer,
initState,
composeWithDevTools(applyMiddleware())
);
}
export const initializeStore = (preloadedState) => {
let _store = store ?? makeStore(preloadedState);
// After navigating to a page with an initial Redux state, merge that state
// with the current state in the store, and create a new store
if (preloadedState && store) {
_store = makeStore({
...store.getState(),
...preloadedState,
});
// Reset the current store
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;
}