Detect custom async errors globally
Middleware
Redux Toolkit · Function
isRejectedWithValue creates a type-guard matcher for rejected createAsyncThunk actions that used rejectWithValue. It can optionally be scoped to one or more thunk action creators.
Call isRejectedWithValue with optional async-thunk action creators to obtain a type guard. The guard returns true only for rejected createAsyncThunk lifecycle actions produced through rejectWithValue; without supplied creators, it can match such actions from any thunk.
isRejectedWithValue(...actionCreators)| Name | Type | Description |
|---|---|---|
actionCreators | AsyncThunkActionCreator[] | Optional one or more async-thunk action creators to constrain the matcher. |
A type-guard function that returns true for matching rejected createAsyncThunk actions created with rejectWithValue.
import { isRejectedWithValue } from '@reduxjs/toolkit'
const matcher = isRejectedWithValue()
const action = {
type: 'request/rejected',
payload: { message: 'Invalid input' },
meta: { rejectedWithValue: true },
error: { message: 'Rejected' },
}
if (matcher(action)) {
console.log(action.payload.message)
}Creates a matcher and uses it as a type guard for a rejected action carrying a value supplied through rejectWithValue.
Middleware
Reducers
Thunk-specific logic
It is a higher-order matcher that returns a type guard for rejected createAsyncThunk actions created with rejectWithValue. Calling the returned function with an action lets TypeScript narrow that action to the matching rejected-action shape.
Follow-up: How would you restrict the match to selected thunks? Pass those thunk action creators to isRejectedWithValue; the resulting matcher applies their matching criteria as well.
With no action creators, it checks whether an action is a rejected async-thunk action whose rejection came from rejectWithValue. This is useful for centralized handling of custom rejection payloads.
Follow-up: What does the payload contain? It contains the value passed to rejectWithValue, while the rejected action's error message is typically 'Rejected'.
You can pass one or more action creators, such as requestThunk1 and requestThunk2, and use the returned predicate in an if statement. The predicate is also a type guard, so the action is narrowed inside that branch.
Follow-up: What is the key behavioral detail with several creators? The documentation states that all supplied matching conditions must match, rather than treating the creators as an either/or list.
createAsyncThunkrejectWithValueisRejectedisFulfilled