Search code examples
javascriptangulartypescriptjavascript-objectsngrx

Ngrx : Cannot assign to read only property 'Property' of object '[Object]'


I'm using ngrx store.

In my state I have to items

export interface ISchedulesState {
  schedulings: ISchedules;
  actualTrips: ISchedule[];
}

Here are my interfaces

export interface ISchedules {
  [key: string]: ISchedule[];
}

export interface ISchedule {
  dest: number;
  data: string
}

In reducer I update actualTrips

export const SchedulingReducers = (
  state = initialSchedulingState,
  action: SchedulesAction
): ISchedulesState => {
  switch (action.type) {
    case ESchedulesActions.GetSchedulesByDate: {
      return {
        ...state
      };
    }
    case ESchedulesActions.GetSchedulesByDateSuccess: {
      return {
        ...state,
        schedulings: action.payload
      };
    }
    case ESchedulesActions.GetSchedulesByTime: {
      let time = action.payload;
      state.actualTrips = [...(state.schedulings[time] || [])]; // if not data return empty array
      return state;
    }
    default:
      return state;
  }
};

But actually I get an error

ERROR TypeError: Cannot assign to read only property 'actualTrips' of object '[object Object]'


Solution

  • The basic principle of Redux pattern is immutability of state and its parts, because it let's us to detect changes just by object reference instead of comparing whole objects.

    In your reducer, you cannot directly assign a property of state (state.actualTrips =), because change detector (and selectors) would not detect it as changed.

    To modify state, you return a copy of the state with new modifications.

      const time = action.payload;
      return {
          ...state,
          actualTrips: [...(state.schedulings[time] || [])]
      }