-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcreateReduxModule.js
40 lines (34 loc) · 1.4 KB
/
createReduxModule.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
const { getStore } = require("./storeRegistry");
const { useSelector } = require("react-redux");
const { createVirtualStore } = require("./VirtualStore");
const mapKeys = (o, f) => {
const r = {};
for (let k in o) r[k] = f(k);
return r;
};
const createSimpleReduxModule = (storeKey, initialState) => {
const [hook, dispatchers, virtualStore] = createReduxModule(storeKey, initialState, {
update: (state, payload) => payload,
});
return [hook, dispatchers.update, virtualStore];
};
const createReduxModule = (storeKey, initialState, reducers, store = getStore()) => {
if (!reducers) return createSimpleReduxModule(storeKey, initialState);
let getQualifiedActionType = type => `${storeKey}-${type}`;
let qualifiedReducers = {};
Object.keys(reducers).map(key => {
return (qualifiedReducers[getQualifiedActionType(key)] = reducers[key]);
});
store.injectReducer(storeKey, (state = initialState, { type, payload }) =>
qualifiedReducers[type] ? qualifiedReducers[type](state, payload) : state
);
return [
(fn = undefined, comparator = undefined) =>
useSelector(storeState => {
return typeof fn === "function" ? fn(storeState[storeKey]) : storeState[storeKey];
}, comparator),
mapKeys(reducers, type => payload => store.dispatch({ type: getQualifiedActionType(type), payload })),
createVirtualStore(store, storeKey),
];
};
module.exports = createReduxModule;