reduxredux-toolkitredux-reducers

Redux Toolkit matcher to determine if exists in state


I have a large reducer where I'm storing all data entities in a flat structure.

I want to seperate this into 2 seperate reducers so that some of the entities are persisted with Redux Persist and some are not.

To acheive this, I'm trying to add a matcher to detect if the state already has the entity and reject if not.

i.e.

  //these cases are used by both reducers
     builder
    .addCase(update, (state, action) => {})
    .addCase(copy, (state, action) => {})
    .addCase(clone, (state, action) => {})
    .addMatcher(isEntityAction, matcher);

function isEntityAction(action: AnyAction): action is PayloadAction {
  return !!action.payload?.entity;
}

function matcher(state, action: AnyAction): action is PayloadAction<any> {
  return state[action.payload?.entity?.entityType] !== undefined;
}

However the matcher is having no effect.

What's the right way to go about this? Thanks


Solution

  • You are misinterpreting addMatcher here.

    The sigature is addMatcher(matcher, reducer) - the matcher can only say "I want to handle this action" or "I do not want to handle it" - it cannot look at the state. It can also not "reject" something.