Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  145] [ 4]  / answers: 1 / hits: 41721  / 5 Years ago, wed, august 21, 2019, 12:00:00

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]'



More From » angular

 Answers
29

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] || [])]
}

[#51748] Tuesday, August 13, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janayr

Total Points: 80
Total Questions: 80
Total Answers: 114

Location: Venezuela
Member since Sat, Aug 22, 2020
4 Years ago
;