Created
March 2, 2018 06:02
-
-
Save brianneisler/0e59d3d72621dbab35c987c23c25f74e to your computer and use it in GitHub Desktop.
Promise Middleware
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
import isPromise from 'is-promise'; | |
const defaultTypes = ['PENDING', 'FULFILLED', 'REJECTED']; | |
export default function promiseMiddleware() { | |
return ({dispatch, getState}) => { | |
return next => action => { | |
if (typeof action === 'function') { | |
return action(dispatch, getState); | |
} | |
if (!isPromise(action.payload)) { | |
return next(action); | |
} | |
const { type, payload, ...rest } = action; | |
const [ PENDING, FULFILLED, REJECTED ] = defaultTypes; | |
/** | |
* Dispatch the first async handler. This tells the | |
* reducer that an async action has been dispatched. | |
*/ | |
next({ | |
type: `${type}_${PENDING}` | |
}); | |
return payload.then( | |
(resolved) => next({type: `${type}_${FULFILLED}`, payload: resolved, ...rest}), | |
(error) => next({type: `${type}_${REJECTED}`, payload: error, ...rest}) | |
); | |
}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment