createThunk - rootstrap/redux-tools GitHub Wiki
createThunk is a function that returns an action that thunkMiddleware will capture and handle.
Arguments
actionNamePrefix(string): A string that will be used as a prefix for the dispatched request, error, success, and reset actions.thunk(function): A function, usually async, that will be awaited for.
Returns
A function that can be used as an action creator. It can receive one or more parameters that will be then fed to the thunk.
The returned actionThunk also has the following action creators:
- request (action type:
${actionNamePrefix}_REQUEST) - success (action type:
${actionNamePrefix}_SUCCESS) - error (action type:
${actionNamePrefix}_ERROR) - reset (action type:
${actionNamePrefix}_RESET)
Example:
const login = createActionWithThunk(
'LOGIN',
async (user, password) => {
const response = await userService.login({ user, password })
return response.data
}
);
dispatch(login('example', 'example'))
This will immediately dispatch login.request() before calling the thunk. Then it will dispatch login.sucess(response.data) or login.error(error) in case an error is thrown inside the thunk.
You can use these to manually dispatch regular actions that match actions automatically dispatched by the middleware when the thunk succeeds or fails. Like this:
dispatch(login.reset())
This actionThunk object implements toString returning the action name prefix.
The rest of the action creators also implement toString returning their respective action names.