Search code examples
reactjsreduxreact-reduxnormalizr

Normalizr - where would I modify an entity?


So I ran ahead and normalized all the entities in my reducers, which means each reducer has a separate entities object. I now realise it makes more sense for one reducer to have all entities in it, then just store IDs (such as currentUser or something) in separate reducers.

This approach makes complete sense for merging in entities from an API response, but I can't work out how I'd change any entity.

For example, where would I do an operation like this?

    case SUBSCRIBER_TOGGLED: {
        let projectSubscriberIDs = cloneDeep(action.payload.project.subscriberIDs);

        let indexIfExists = projectSubscriberIDs.indexOf(action.payload.user.id);

        if(indexIfExists != -1){
            projectSubscriberIDs.splice(indexIfExists, 1);
        }else{
            projectSubscriberIDs.push(action.payload.user.id);
        }

        return {
            ...state,
            entities: {
                ...state.entities,
                projects: {
                    ...state.entities.projects,
                    [action.payload.project.id]: {
                        ...action.payload.project,
                        subscriberIDs: projectSubscriberIDs
                    }
                }
            }
        }
    }
  • we can't work this out earlier in an action, as actions can't know what's in state
  • we can't do this in a reducer that doesn't contain the relevant entities, as reducers can't/shouldn't access other reducers
  • it feels wrong to do all of these in the entities reducer, as it'll become an enormous mess

Anyone have any insights here?


Solution

  • A few thoughts: