A cache middleware for redux
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 cache = store => next => action => { | |
// handle FETCH action only | |
if (action.type !== 'FETCH') { | |
return next(action); | |
} | |
// check if cache is available | |
const data = window['__data']; | |
if (!data) { | |
// forward the call to live middleware | |
return next(action); | |
} | |
return store.dispatch({ type: 'RECEIVE', payload: { data: `${data} (from cache)` } }); | |
} | |
export default cache; |
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 live = store => next => action => { | |
// handle FETCH action only | |
if (action.type !== 'FETCH') { | |
return next(action); | |
} | |
// TODO fetch from live source | |
const data = 'foo'; | |
// store data to cache | |
window['__data'] = data; | |
return store.dispatch({ type: 'RECEIVE', payload: { data } }); | |
} | |
export default live; |
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 mainApp = (state = { }, action) => { | |
switch (action.type) { | |
case 'FETCH': | |
case 'RECEIVE': | |
return { | |
...state, | |
...action.payload, | |
} | |
default: | |
return state; | |
} | |
} | |
export default mainApp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment