Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update states of multiple reducers with a single action in ngrx store?

I have multiple reducers in my application which are combined in app.reducers.ts. When my action happens state of one reducer should be update with single value from current state of the other reducer(so unplanned delivery will become scheduled) and then remove that value from state of second reducer. Here is how I can delete it, but before doing this I need to update other state.

case UNPLANNED_ACTIONS.REMOVE_UNPLANNED_DELIVERY:
        return Object.assign({}, state, {
            deliveries: state.deliveries.filter(delivery => delivery.deliveryId !== payload.deliveryId)
        });

Calling 2 actions is very bad from application point of view. So I need to somehow handle this on the higher level.

like image 450
Blind Despair Avatar asked Oct 25 '25 00:10

Blind Despair


1 Answers

Your store can have multiple reducers, with each acting separately on the action.

For example, you can define them like

export function reducer(
  state = initialState,
  action: fromMyStoreActions.DeliveryAction
): AppState{

  switch (action.type) {
    case UNPLANNED_ACTIONS.REMOVE_UNPLANNED_DELIVERY:
         return Object.assign({}, state, {
              deliveries: state.deliveries.filter(delivery => delivery.deliveryId !== payload.deliveryId)
         });
    ...
}

// Another Reducer
export function reducer(
      state = initialState,
      action: fromMyStoreActions.DeliveryAction
    ): AppState{

      switch (...)
....

And then pass all the reducers to ngrx in the module like

StoreModule.forRoot(reducers)

For a good example, see this repo

like image 189
rayray Avatar answered Oct 26 '25 16:10

rayray