Search code examples
reduxredux-saganormalizr

Structuring redux, redux-saga and normalizr


So I would like to use these three technologies. My idea is to have a reducer which handles all my entities, aided by normalizr.

redux-saga would listen for ENTITIES_REQUESTED action, run a saga which requests the entities, and makes a ENTITIES_RECEIVED action, which would be handled by a reducer which calls normalizr and stores the entities in the entities slice.

For deleting an entity, two things have to happen: the entity must be removed from the state, and a side effect must happen which will remove the entity from the server (side point: I know some will claim that removing from state is also a side effect, but I don't think redux-saga works on that notion).

So I can have a ENTITY_REMOVED action, which will remove the entity from the state, and a saga listening for that, which will handle the api call.

Now let's say I have a table, with a bulk delete feature for a table. The table is "powered" by a reducer that accepts an action DATA_OPTIONS_SET. The reducer updates things like current page, filters, etc. There would also be a saga from listens to this and calls the API to return the new data set.

I would like to have a bulk delete feature which at a high level, deletes all the entities, and when that is done, refresh the table.

If I loop over the entities to delete, and dispatch an ENTITY_REMOVED action, I will how no way of knowing when those deletes are done, so that I could refresh the table.

If I manually call the saga that deletes the entities, ENTITY_REMOVED will never have been dispatched, so the entity is not removed from the store.

Does this mean my architecture is incorrect and I took a wrong turn somewhere?


Solution

  • I would approach your problem as follows: create delete saga which would

    1. Wait for ENTITIY_REMOVE_REQUEST action with entity id as parameter
    2. Call an appropriate endpoint to delete entity from server
    3. If api call was success dispatch ENTITY_REMOVED action which will remove entity from state.

    Of course this is not the only option and much details will depend on how your api is build. Instead of removing each entity manually in point 3. you could dispatch an action that will fetch all entities from the server and updated your whole state with new entities list, or you could bulk up and pass all entities that need to be deleted in single api call in point 2.