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

泄露秘密 提交于 2019-12-24 11:57:17

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/44115329/how-to-update-states-of-multiple-reducers-with-a-single-action-in-ngrx-store

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!