Created
April 11, 2018 11:55
-
-
Save mmathys/a7cc4d674efad4e25dd1fe7476cb4073 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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