I was using redux toolkit. What got me confused in CreateReducer is that I can't quite understand the difference between .addCase and .addMatcher?
addCase
will run the reducer if the dispatched action's action.type
field exactly matches the string that you provideaddMatcher
will run the reducer if the callback function you provide returns true
, and it's up to you to decide how the matching behavior works. Typically this is done by looking to see if the action.type
field is a partial match, such as return action.type.endsWith("/pending")
Simple Example containing both addCase
and addMatcher
along with addDefaultCase
to conclude:
import { createAction, createReducer } from '@reduxjs/toolkit'
const increment = createAction('counter/increment')
const initialState = { value: 0 }
const counterReducer = createReducer(initialState, (builder) => {
builder
.addCase(increment, (state, action) => {
// Handle increment action here...
state.value++
})
.addMatcher((action) => {
return action.type.endsWith("rejected");
}, (state, action)=>{
// Handle actions whose names end with "rejected" here...
})
.addDefaultCase((state, action)=>{
// Handle default cases here...
})
})