I'm refactoring my reducers to use the redux-toolkit's createSlice
.
Now I have a very event-based reducer and sometimes a similar state update for different actions is required
.
With the original switch/case
statement this was no issue:
case ActionTypes.CREATION_CANCELLED:
case ActionTypes.NEW_MARKER_INFOWINDOW_CLOSED:
case ActionTypes.MARKER_SELECTED:
return {...state, isCreating: false};
Is this kind of behaviour possible with a createSlice
function?
You can do this using the
extraReducers
"builder callback" notation. With this notation you create a reducer by adding cases to abuilder
object. The first argument of thebuilder.addMatcher
function determines which action types match this case.If your actions share a common string format, you can use string-based matchers like
action.type.endsWith('/rejected')
to handle allrejected
actions the same way.Otherwise you can define your own custom matcher function that takes an
action
and returns aboolean
of whether or not it's a match.Since we want to match multiple action types, we can create a helper for that.
We can use this with your existing
string
constants:Or with Redux Toolkit action creators: