Skip to content

Instantly share code, notes, and snippets.

@mmathys
Created April 11, 2018 11:55
Show Gist options
  • Save mmathys/a7cc4d674efad4e25dd1fe7476cb4073 to your computer and use it in GitHub Desktop.
Save mmathys/a7cc4d674efad4e25dd1fe7476cb4073 to your computer and use it in GitHub Desktop.
import {
ASYNC_START,
ASYNC_END
} from './constants/actionTypes.jsx';
const promiseMiddleware = store => next => action => {
if (isPromise(action.payload)) {
store.dispatch({ type: ASYNC_START, subtype: action.type });
const currentView = store.getState().viewChangeCounter;
const skipTracking = action.skipTracking;
action.payload.then(
res => {
const currentState = store.getState()
if (!skipTracking && currentState.viewChangeCounter !== currentView) {
return
}
console.log('RESULT', res);
action.payload = res;
store.dispatch({ type: ASYNC_END, promise: action.payload });
store.dispatch(action);
},
error => {
const currentState = store.getState()
if (!skipTracking && currentState.viewChangeCounter !== currentView) {
return
}
console.log('ERROR', error);
action.error = true;
action.payload = error.response.body;
if (!action.skipTracking) {
store.dispatch({ type: ASYNC_END, promise: action.payload });
}
store.dispatch(action);
}
);
return;
}
next(action);
};
function isPromise(v) {
return v && typeof v.then === 'function';
}
export { promiseMiddleware }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment