'What is 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?



Solution 1:[1]

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 })
    );
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1