-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.mjs
61 lines (46 loc) · 1.53 KB
/
test.mjs
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
import { createStore, combineReducers, applyMiddlewares } from './src';
// count reducer
const initialState = 0;
const countReducer = (state = initialState, action) => {
switch (action.type) {
case 'increment': {
return state + action.count;
}
default: {
return state;
}
}
};
const wait = (ms) => new Promise((res) => setTimeout(res, ms));
const incrementAction = (count) => ({ type: 'increment', count });
const thunkAction = () => (dispatch, getState) => {
wait(1000).then(() => {
dispatch(incrementAction(10));
});
};
const thunkAction2 = () => (dispatch) => {
dispatch(incrementAction(1));
dispatch(incrementAction(2));
};
// middlewares
const logger = (store) => (next) => (action) => {
console.log('will dispatch:', action);
// Call the next dispatch method in the middleware chain.
const returnValue = next(action);
console.log('state after dispatch:', store.getState());
// This will likely be the action itself, unless
// a middleware further in chain changed it.
return returnValue;
};
const thunk = (store) => (next) => (action) => {
if (typeof action === 'function') {
return action(store.dispatch, store.getState);
}
return next(action);
};
const rootReducer = combineReducers({ counter: countReducer });
const store = createStore(rootReducer, {}, applyMiddlewares([thunk, logger]));
console.log('initial state: ', store.getState());
store.subscribe(() => console.log(`State changed!`, store.getState()));
store.dispatch(incrementAction(1));
store.dispatch(thunkAction2());