Skip to content

Instantly share code, notes, and snippets.

@sfrdmn
Created December 1, 2017 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfrdmn/faa99912094c39b24a1ae5e34e43a61e to your computer and use it in GitHub Desktop.
Save sfrdmn/faa99912094c39b24a1ae5e34e43a61e to your computer and use it in GitHub Desktop.
mcr_post_05
// 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