-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
58 lines (45 loc) · 1.41 KB
/
index.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { combineReducers, compose } from 'redux';
export const createDynamicMiddleware = (m) => {
let mdw = m || [];
return {
middleware: ({ getState, dispatch }) => next => (action) => {
const middlewareAPI = {
getState,
dispatch: act => dispatch(act),
};
const chain = mdw.map(m => m(middlewareAPI));
return compose(...chain)(next)(action);
},
add: (m, order) => {
if (!order) {
mdw.push(m);
} else {
mdw.splice(order, 0, m);
}
},
remove: (middlewareFn) => {
const index = mdw.findIndex(d => d === middlewareFn);
mdw.splice(index, 1);
},
}
};
export const createDynamicReducer = rdcrs => {
let reducers = rdcrs || {};
return {
add: (store, reducer, namespace) => {
reducers[namespace] = compose(reducers[namespace] || (a => a), reducer);
store.replaceReducer(combineReducers({ ...reducers }));
},
remove: (store, namespace) => {
delete reducers[namespace];
const stateKeys = Object.keys(store.getState());
const reducerKeys = new Set(Object.keys(reducers));
stateKeys
.filter(key => !reducerKeys.has(key)) // state has a key that doesn't have a corresponding reducer
.forEach(key => {
reducers[key] = state => state === undefined ? null : state;
});
store.replaceReducer(combineReducers({ ...reducers }));
},
}
};