Centralize thunk failure handling
Handle failures from selected async thunks in a slice without writing separate reducers for each rejected action.
Redux Toolkit · Function
isRejected creates a type-safe matcher for rejected createAsyncThunk lifecycle actions. Optionally provide thunk action creators to limit which rejected actions match.
isRejected is a higher-order matcher for Redux Toolkit async-thunk lifecycle actions. Call it with optional thunk action creators to obtain a type guard that recognizes matching rejected actions, then use the returned matcher with addMatcher or middleware.
isRejected(...actionCreators)| Name | Type | Description |
|---|---|---|
actionCreators | AsyncThunk[] | Optional one or more action creators whose rejected lifecycle actions should match. |
A type guard function that returns true for matching rejected createAsyncThunk lifecycle actions.
import { configureStore, createAsyncThunk, createSlice, isRejected } from '@reduxjs/toolkit'
const loadUser = createAsyncThunk('user/load', async () => {
throw new Error('Network failure')
})
const slice = createSlice({
name: 'user',
initialState: { error: '' },
reducers: {},
extraReducers: (builder) => {
builder.addMatcher(isRejected(loadUser), (state, action) => {
state.error = action.error.message ?? 'Request failed'
})
},
})
const store = configureStore({ reducer: slice.reducer })
store.dispatch(loadUser())The matcher narrows rejected lifecycle actions from the selected thunk, allowing a reducer to handle its error.
Handle failures from selected async thunks in a slice without writing separate reducers for each rejected action.
Filter rejected async-thunk actions in middleware for logging, notifications, or telemetry.
Narrow an unknown Redux action before reading rejected-action fields in TypeScript.
isRejected accepts zero or more async-thunk action creators and returns a type guard for rejected lifecycle actions. With creators supplied, only rejected actions from those creators match.
Follow-up: How would you detect rejected actions carrying custom data? Use isRejectedWithValue, which checks for a rejected action with a payload.
The returned matcher can be passed to builder.addMatcher or used as a predicate in middleware. A successful match narrows the action to a rejected async-thunk action.
Follow-up: How can matching be limited to one thunk? Pass that thunk's action creator to isRejected when creating the matcher.
It identifies rejected actions from the createAsyncThunk promise lifecycle. It is not a general test for arbitrary actions whose type happens to end in rejected.
Follow-up: What matcher covers every rejected action regardless of payload? isRejected matches rejected lifecycle actions, while isRejectedWithValue focuses on payload-bearing rejections.
isPendingisFulfilledisRejectedWithValuecreateAsyncThunkaddMatcher