Created
December 1, 2017 15:57
-
-
Save sfrdmn/faa99912094c39b24a1ae5e34e43a61e to your computer and use it in GitHub Desktop.
mcr_post_05
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
// Here we have a function which accepts a map of async states to action types | |
// as well as a thunk creator. It will yield a new thunk creator which wraps | |
// the provided one with our async state logic | |
const asyncActionCreator = (asyncTypes, createThunk) => (...args) => { | |
const thunk = createThunk(...args); | |
return (dispatch) => { | |
dispatch({ type: asyncTypes.pending }) | |
// We assume here that the wrapped thunk produces a Promise | |
// We call dispatch on the thunk (it's just a normal thunk, after all) | |
// and since dispatch yields its result, we can utilize the returned | |
// Promise | |
return dispatch(thunk) | |
.then(payload => ({ | |
type: asyncTypes.complete, | |
payload | |
})) | |
.catch(err => ({ | |
type: asyncTypes.error, | |
error: true, | |
payload: error | |
})) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment