createAsyncThunk
#
#
OverviewA function that accepts a Redux action type string and a callback function that should return a promise. It generates promise lifecycle action types based on the action type prefix that you pass in, and returns a thunk action creator that will run the promise callback and dispatch the lifecycle actions based on the returned promise.
This abstracts the standard recommended approach for handling async request lifecycles.
It does not generate any reducer functions, since it does not know what data you're fetching, how you want to track loading state, or how the data you return needs to be processed. You should write your own reducer logic that handles these actions, with whatever loading state and processing logic is appropriate for your own app.
Sample usage:
#
ParameterscreateAsyncThunk
accepts three parameters: a string action type
value, a payloadCreator
callback, and an options
object.
type
#
A string that will be used to generate additional Redux action type constants, representing the lifecycle of an async request:
For example, a type
argument of 'users/requestStatus'
will generate these action types:
pending
:'users/requestStatus/pending'
fulfilled
:'users/requestStatus/fulfilled'
rejected
:'users/requestStatus/rejected'
payloadCreator
#
A callback function that should return a promise containing the result of some asynchronous logic. It may also return a value synchronously. If there is an error, it should either return a rejected promise containing an Error
instance or a plain value such as a descriptive error message or otherwise a resolved promise with a RejectWithValue
argument as returned by the thunkAPI.rejectWithValue
function.
The payloadCreator
function can contain whatever logic you need to calculate an appropriate result. This could include a standard AJAX data fetch request, multiple AJAX calls with the results combined into a final value, interactions with React Native AsyncStorage
, and so on.
The payloadCreator
function will be called with two arguments:
arg
: a single value, containing the first parameter that was passed to the thunk action creator when it was dispatched. This is useful for passing in values like item IDs that may be needed as part of the request. If you need to pass in multiple values, pass them together in an object when you dispatch the thunk, likedispatch(fetchUsers({status: 'active', sortBy: 'name'}))
.thunkAPI
: an object containing all of the parameters that are normally passed to a Redux thunk function, as well as additional options:dispatch
: the Redux storedispatch
methodgetState
: the Redux storegetState
methodextra
: the "extra argument" given to the thunk middleware on setup, if availablerequestId
: a unique string ID value that was automatically generated to identify this request sequencesignal
: anAbortController.signal
object that may be used to see if another part of the app logic has marked this request as needing cancelation.rejectWithValue(value, [meta])
: rejectWithValue is a utility function that you canreturn
(orthrow
) in your action creator to return a rejected response with a defined payload and meta. It will pass whatever value you give it and return it in the payload of the rejected action. If you also pass in ameta
, it will be merged with the existingrejectedAction.meta
.fulfillWithValue(value, meta)
: fulfillWithValue is a utility function that you canreturn
in your action creator tofulfill
with a value while having the ability of adding tofulfilledAction.meta
.
The logic in the payloadCreator
function may use any of these values as needed to calculate the result.
#
OptionsAn object with the following optional fields:
condition(arg, { getState, extra } ): boolean
: a callback that can be used to skip execution of the payload creator and all action dispatches, if desired. See Canceling Before Execution for a complete description.dispatchConditionRejection
: ifcondition()
returnsfalse
, the default behavior is that no actions will be dispatched at all. If you still want a "rejected" action to be dispatched when the thunk was canceled, set this flag totrue
.idGenerator(): string
: a function to use when generating therequestId
for the request sequence. Defaults to use nanoid.serializeError(error: unknown) => any
to replace the internalminiSerializeError
method with your own serialization logic.getPendingMeta({ arg, requestId }, { getState, extra }): any
: a function to create an object that will be merged into thependingAction.meta
field.
#
Return ValuecreateAsyncThunk
returns a standard Redux thunk action creator. The thunk action creator function will have plain action creators for the pending
, fulfilled
, and rejected
cases attached as nested fields.
Using the fetchUserById
example above, createAsyncThunk
will generate four functions:
fetchUserById
, the thunk action creator that kicks off the async payload callback you wrotefetchUserById.pending
, an action creator that dispatches an'users/fetchByIdStatus/pending'
actionfetchUserById.fulfilled
, an action creator that dispatches an'users/fetchByIdStatus/fulfilled'
actionfetchUserById.rejected
, an action creator that dispatches an'users/fetchByIdStatus/rejected'
action
When dispatched, the thunk will:
- dispatch the
pending
action - call the
payloadCreator
callback and wait for the returned promise to settle - when the promise settles:
- if the promise resolved successfully, dispatch the
fulfilled
action with the promise value asaction.payload
- if the promise resolved with a
rejectWithValue(value)
return value, dispatch therejected
action with the value passed intoaction.payload
and 'Rejected' asaction.error.message
- if the promise failed and was not handled with
rejectWithValue
, dispatch therejected
action with a serialized version of the error value asaction.error
- if the promise resolved successfully, dispatch the
- Return a fulfilled promise containing the final dispatched action (either the
fulfilled
orrejected
action object)
#
Promise Lifecycle ActionscreateAsyncThunk
will generate three Redux action creators using createAction
: pending
, fulfilled
, and rejected
. Each lifecycle action creator will be attached to the returned thunk action creator so that your reducer logic can reference the action types and respond to the actions when dispatched. Each action object will contain the current unique requestId
and arg
values under action.meta
.
The action creators will have these signatures:
To handle these actions in your reducers, reference the action creators in createReducer
or createSlice
using either the object key notation or the "builder callback" notation. (Note that if you use TypeScript, you should use the "builder callback" notation to ensure the types are inferred correctly):
#
Handling Thunk Results#
Unwrapping Result ActionsThunks may return a value when dispatched. A common use case is to return a promise from the thunk, dispatch the thunk from a component, and then wait for the promise to resolve before doing additional work:
The thunks generated by createAsyncThunk
will always return a resolved promise with either the fulfilled
action object or rejected
action object inside, as appropriate.
The calling logic may wish to treat these actions as if they were the original promise contents. Redux Toolkit exports an unwrapResult
function that can be used to extract the payload
of a fulfilled
action or to throw either the error
or, if available, payload
created by rejectWithValue
from a rejected
action:
#
Checking Errors After DispatchingNote that this means a failed request or error in a thunk will never return a rejected promise. We assume that any failure is more of a handled error than an unhandled exception at this point. This is due to the fact that we want to prevent uncaught promise rejections for those who do not use the result of dispatch
.
If your component needs to know if the request failed, use unwrapResult
and handle the re-thrown error accordingly.
#
Handling Thunk ErrorsWhen your payloadCreator
returns a rejected promise (such as a thrown error in an async
function), the thunk will dispatch a rejected
action containing an automatically-serialized version of the error as action.error
. However, to ensure serializability, everything that does not match the SerializedError
interface will have been removed from it:
If you need to customize the contents of the rejected
action, you should catch any errors yourself, and then return a new value using the thunkAPI.rejectWithValue
utility. Doing return rejectWithValue(errorPayload)
will cause the rejected
action to use that value as action.payload
.
The rejectWithValue
approach should also be used if your API response "succeeds", but contains some kind of additional error details that the reducer should know about. This is particularly common when expecting field-level validation errors from an API.
#
Cancellation#
Canceling Before ExecutionIf you need to cancel a thunk before the payload creator is called, you may provide a condition
callback as an option after the payload creator. The callback will receive the thunk argument and an object with {getState, extra}
as parameters, and use those to decide whether to continue or not. If the execution should be canceled, the condition
callback should return a literal false
value:
If condition()
returns false
, the default behavior is that no actions will be dispatched at all. If you still want a "rejected" action to be dispatched when the thunk was canceled, pass in {condition, dispatchConditionRejection: true}
.
#
Canceling While RunningIf you want to cancel your running thunk before it has finished, you can use the abort
method of the promise returned by dispatch(fetchUserById(userId))
.
A real-life example of that would look like this:
- TypeScript
- JavaScript
After a thunk has been cancelled this way, it will dispatch (and return) a "thunkName/rejected"
action with an AbortError
on the error
property. The thunk will not dispatch any further actions.
Additionally, your payloadCreator
can use the AbortSignal
it is passed via thunkAPI.signal
to actually cancel a costly asynchronous action.
The fetch
api of modern browsers already comes with support for an AbortSignal
:
- TypeScript
- JavaScript
#
Checking Cancellation Status#
Reading the Signal ValueYou can use the signal.aborted
property to regularly check if the thunk has been aborted and in that case stop costly long-running work:
- TypeScript
- JavaScript
#
Listening for Abort EventsYou can also call signal.addEventListener('abort', callback)
to have logic inside the thunk be notified when promise.abort()
was called.
This can for example be used in conjunction with an axios CancelToken
:
- TypeScript
- JavaScript
#
Examples- Requesting a user by ID, with loading state, and only one request at a time:
Using rejectWithValue to access a custom rejected payload in a component
Note: this is a contrived example assuming our userAPI only ever throws validation-specific errors
- TypeScript
- JavaScript