Skip to content

Instantly share code, notes, and snippets.

@dengjonathan
Created February 15, 2017 01:12
Show Gist options
  • Save dengjonathan/d100d51c9e384c2a2e686d3a9171ae53 to your computer and use it in GitHub Desktop.
Save dengjonathan/d100d51c9e384c2a2e686d3a9171ae53 to your computer and use it in GitHub Desktop.
redux middleware example
const redux = require('redux');
const reducer = (state={}, action) => {
switch(action.type) {
case 'START':
return Object.assign({}, state, {start: Date.now(), interval: action.interval});
case 'TICK':
return Object.assign({}, state, {elapsed: action.currentTime - state.start});
case 'STOP':
return Object.assign({}, state, {interval: null});
}
return state;
};
const timerMiddleware = store => next => action => {
if (action.type === 'START') {
action.interval = setInterval(() => store.dispatch({
type: 'TICK',
currentTime: Date.now()
}), 1000);
}
if (action.type === 'STOP') {
clearInterval(store.getState().interval);
}
next(action);
}
const middleWare = redux.applyMiddleware(timerMiddleware);
const store = redux.createStore(reducer, middleWare);
store.subscribe(() => console.log(store.getState().elapsed));
store.dispatch({type: 'START'});
setTimeout(() => store.dispatch({type: 'STOP'}), 5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment