Created
February 15, 2017 01:12
-
-
Save dengjonathan/d100d51c9e384c2a2e686d3a9171ae53 to your computer and use it in GitHub Desktop.
redux middleware example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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