I was using redux toolkit. What got me confused in CreateReducer is that I can't quite understand the difference between .addCase and .addMatcher?
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")To add more clarity to popular explanations: builder.addCase can be viewed as a shorthand for builder.addMatcher, where an action is matched by its type property. So, the following two pieces of code are functionally equivalent:
1.
export default createReducer(initialState, (builder) => {
builder
.addCase(actions.openModal, (state, { payload }) => ({ ...state, modalData: payload, isModalOpen: true }))
.addCase(actions.closeModal, (state) => ({ ...state, isModalOpen: false }));
});
export default createReducer(initialState, (builder) => {
builder
.addMatcher(
({ type }) => type === actions.openModal.type,
(state, { payload }) => ({ ...state, modalData: payload, isModalOpen: true })
)
.addMatcher(
({ type }) => type === actions.closeModal.type,
(state) => ({ ...state, isModalOpen: false })
);
});