Track unhandled actions
Increment a diagnostic counter whenever an action is not recognized by a reducer.
Redux Toolkit · Module
builder.addDefaultCase registers a fallback reducer for actions not handled by a specific case or matcher. It is used in the builder callback passed to createReducer and can be chained with other builder methods.
Call addDefaultCase while constructing a reducer with the builder callback. Its reducer runs only when the dispatched action matched neither an explicit case nor any matcher; otherwise, the existing state is preserved or another handler updates it.
builder.addDefaultCase(reducer)| Name | Type | Description |
|---|---|---|
reducer | CaseReducer<State, Action> | Reducer function used as the fallback when no case or matcher reducer handles the action. |
The builder object, allowing chained reducer-builder calls.
createReducer, where the builder exposes reducer-registration methods.import { createReducer } from '@reduxjs/toolkit'
const reducer = createReducer({ otherActions: 0 }, (builder) => {
builder.addCase('counter/increment', (state) => {
state.otherActions = 0
})
builder.addDefaultCase((state) => {
state.otherActions += 1
})
})
console.log(reducer(undefined, { type: 'counter/increment' }))
console.log(reducer(undefined, { type: 'counter/unknown' }))The first action is handled by its specific case, while the unknown action uses the fallback reducer.
Increment a diagnostic counter whenever an action is not recognized by a reducer.
Apply a generic fallback transformation after excluding all known action types and matchers.
Leave state unchanged for unmatched actions by omitting a default reducer entirely.
builder.addDefaultCase run?addDefaultCase registers a fallback reducer for actions that were not handled by any case reducer or matcher. It is analogous to a default branch in a switch, but is configured through the reducer builder.
Follow-up: What happens if no case, matcher, or default reducer handles an action? The reducer returns the original state unchanged.
addDefaultCase receive?Its argument is a reducer function that receives the current state and the action. It is invoked only when no explicit case reducer and no matcher reducer ran for the action.
Follow-up: Can the fallback run after a matcher? No; if a matcher reducer executes, the default reducer does not execute for that action.
addDefaultCase?The method can be chained with other builder methods, but the registration order is constrained. Case reducers and matchers must be added before the default case, and only one default case is allowed.
Follow-up: How would multiple fallback behaviors be represented? Combine their logic in one default reducer or use matchers for distinct conditions before it.
createReducerbuilder.addCasebuilder.addMatcherextraReducers