Created
December 8, 2017 11:56
-
-
Save vzaidman/2ad5ad5606d98c9939abe2c88b1cf1bf 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
// 1. you pass the base name of actions, and an async function | |
export default function makeThunkAsyncActionCreator(baseName, asyncFn) { | |
// 2. an async action creator is created to indicate the asyncFn progress | |
const actionCreator = makeAsyncActionCreator(baseName) | |
// 3. thunk action creator is what returns from "makeThunkAsyncActionCreator" and it is ready to be called | |
const thunkActionCreator = (...args) => (dispatch, getState) => { | |
// 4. when the action creator is called with certain arguments (...args), we dispatch a pending action | |
dispatch(actionCreator()) | |
// 5. and then we launch the action with the required args | |
return Promise.resolve() | |
.then(() => asyncFn(...args)) | |
.then(data => { | |
// 6. when the promise ends, we dispatch a success action with the data returned | |
return dispatch(actionCreator.success(data)) | |
}) | |
.catch(err => { | |
// 7. if the rejects, we dispatch a failure action with the error returned | |
return dispatch(actionCreator.failure(err)) | |
}) | |
} | |
} | |
return thunkActionCreator | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment