DevLoverUmar
DevLoverUmar

Reputation: 14011

How to perform same state transitions for multiple actions in a Reducer

I have created unique Actions for My App as per the suggestions of Mike Ryan in this video But I have some Actions causing the same state transitions. How to achieve the same state transition without by-passing the Best Practices i.e., calling a common Action for two different events?

My Actions are

export const rawSignalEditInplace = createAction(
  RawSignalsActionTypes.RAW_SIGNAL_EDIT_INPLACE,
  props<{ signal: RawSignal }>()
);

export const rawSignalEdit = createAction(
  RawSignalsActionTypes.RAW_SIGNAL_EDIT,
  props<{ signal: RawSignal }>()
);

My Reducer is

on(rawSignalsActions.rawSignalEditInplace, (state, { signal }) => {
return {
  ...state,
  selectedRawSignal: entitiesSelectors.selectEntities(state)[signal.id]
 };
}),
on(rawSignalsActions.rawSignalEdit, (state, { signal }) => ({
  ...state,
  selectedRawSignal: entitiesSelectors.selectEntities(state)[signal.id]
})),

Upvotes: 13

Views: 8949

Answers (1)

Will Alexander
Will Alexander

Reputation: 3571

You can create one reducer for multiple actions:

on(
  rawSignalsActions.rawSignalEditInplace,
  rawSignalsActions.rawSignalEdit,
  (state, { signal }) => {...}
)

Keeping your actions separate allows you to better track where actions are being dispatched from and helps you to stay modular in case you want to change things in the future. I personally recommend the multiple actions -> one reducer pattern for this reason, although others may also work.

Upvotes: 31

Related Questions