Skip to content

Instantly share code, notes, and snippets.

@tonnguyen
Created February 13, 2018 21:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonnguyen/54ceb391c718a1f9e06e55810cbeaac4 to your computer and use it in GitHub Desktop.
Save tonnguyen/54ceb391c718a1f9e06e55810cbeaac4 to your computer and use it in GitHub Desktop.
A cache middleware for redux
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;
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;
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