Search code examples
angularreduxngrxngrx-store

How to update part of the state property using Ngrx reducer in Angular 8


Here is my initial state. It just adds the name but not under car class as the correct object

export const initialState: CustomerState = {
  customer: new Customer(),
};

export class Customer{
id: number;
age: number;
cars: carClass;
phoneNumbers: string[];
}

export class carClass{
name:string;
citiesRegistered:string[];
}

Here is my reducer. I am trying to update the state but I am not sure how can I update the nested component of the class

export const _customerReducer = createReducer(
  initialState,
  on(addNameToCustomerCarRequest , (state, action) => ({
    ...state,
    customer: { ...state.customer, cars: action.name} 
   
  })),

);

Here is the action to update just the name of the car class

export const addNameToCustomerCarRequest = createAction(
  '[Customer Component] Add Name to customer car request ',
  props<{ name: string }>()
);


Solution

  • Try this:

    export const _customerReducer = createReducer(
      initialState,
      on(addNameToCustomerCarRequest , (state, action) => ({
        ...state,
        customer: { ...state.customer, cars: { ...state.cars, name: action.name } } 
       
      })),
    
    );
    
    This is the new syntax and I am not familiar with it. It should either be `action.payload.name` or `action.name`.