Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { createStore, applyMiddleware } = require('redux');
- const initialState = { count: 0 };
- const incrementReducer = (state = initialState, action) => {
- switch (action.type) {
- case 'INC': return { count: Math.min(10, state.count + 1) };
- case 'DEC': return { count: state.count - 1 };
- case 'RND': return { count: state.count + action.amt };
- default: return state;
- }
- };
- const uselessMW = store => next => (action) => {
- console.log(action);
- next(action);
- };
- const blockDec = store => next => (action) => {
- if (action.type !== 'DEC') {
- next(action);
- }
- };
- const delayAction = store => next => (action) => {
- setTimeout(() => {
- next(action);
- }, 1500);
- };
- const randomRequest = () => {
- const randomDelayTimeout = (Math.random() * 2000) + 1000;
- const randomDelayPromise = new Promise((resolve) => {
- setTimeout(resolve, randomDelayTimeout);
- });
- return randomDelayPromise
- .then(() => Math.floor(Math.random() * 5) - 2);
- };
- const makeRandomRequestMW = store => next => (action) => {
- if (action.type === 'REQ') {
- randomRequest()
- .then((amt) => {
- store.dispatch({ type: 'RND', amt });
- });
- } else {
- next(action);
- }
- };
- // const getUsersMW = store => next => (action) => {
- // if (action.type === 'FETCH_USERS') {
- // store.dispatch({ type: 'FETCH_USERS_PENDING' });
- // getUsersFromAPI()
- // .then((users) => {
- // store.dispatch({ type: 'FETCH_USERS_SUCCESS', users });
- // }, (error) => {
- // store.dispatch({ type: 'FETCH_USERS_ERROR', error });
- // });
- // } else {
- // next(action);
- // }
- // };
- const incrementAction = { type: 'INC' };
- const decrementAction = { type: 'DEC' };
- const requestRandomIncAction = { type: 'REQ' };
- const store = createStore(incrementReducer, applyMiddleware(uselessMW, makeRandomRequestMW));
- console.log(store.getState());
- const unsubscribe = store.subscribe(() => {
- console.log(store.getState());
- });
- setInterval(() => {
- store.dispatch(requestRandomIncAction);
- }, 1500);
- // setInterval(() => {
- // store.dispatch(incrementAction);
- // }, 2000);
- // setInterval(() => {
- // store.dispatch(decrementAction);
- // }, 3400);
- // setTimeout(unsubscribe, 10000);
Add Comment
Please, Sign In to add comment