Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const promiseMiddleware = store => next => action => {
- // if the action's payload is a promise, trigger this middleware
- if (isPromise(action.payload)) {
- // trigger UI's loading state
- store.dispatch({ type: 'ASYNC_START', subtype: action.type });
- // let promise succeed/fail
- action.payload.then(
- // if it succeeds, mutate payload into the promised data and
- // dispatch action to store
- res => {
- action.payload = res;
- store.dispatch(action);
- },
- // failure => set an error flag on action and mutate payload into
- // the error message. dispatch action to store
- error => {
- action.error = true;
- action.payload = error.response.body;
- store.dispatch(action);
- }
- );
- return;
- }
- // if the action payload is not a promise, send the action over to the next middleware
- // or dispatch it to the store if this is the last middleware in the chain
- next(action);
- }
- function isPromise(v) {
- return v && typeof v.then === 'function';
- }
- export {
- promiseMiddleware
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement