简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM