How to execute buisness logic in NgRx reducers

689 Views Asked by At

Hi am using NgRx store for state management in my angular project.

My goal is to clear few state properties on action dispatch. The array of property names are passed to the action.

// Action

export const clearFields = createAction(
    '[SC Base Data] Clear Fields',
    props<{ fields: string[] }>()
);

// Reducers

on(SCActions.clearFields, (state: SCState,fields: string[]) => ({
        ...state,
        
        SCData: {
            ...state.SCData
        }
    })),

/ How can iterate over fields array and set the state properties value as blank

1

There are 1 best solutions below

0
Will Alexander On

If by "blank" you mean null, I believe what you're looking for is something along these lines:

on(SCActions.clearFields, (state: SCState, fields: string[]) => ({
  // create an Object whose keys are all elements of fields and every value is null
  const clearedState = {};
  fields.forEach(field => {
    clearedState[field] = null;
  });
  // return new copy of state nulling all fields from fields array
  return {
    ...state,
    ...clearedState
  };
}))