I have the following structure
export interface MyStructure {
id: string
values: Array<MyObject>
}
In my store I have an action that call the following
const ADD_OBJECT= (state: State, action: featureAction.AddObject) => {
const vals= state.entities[action.payload.objId].values;
vals.concat(action.payload.newObj);
return featureAdapter.updateOne({
id: action.payload.routeId,
changes: {
waypoints : [...vals]
},
}, state);
};
but this never update my store...
I also tried
changes: {
waypoints : new Array<MyObject>
}
the only way I made it work was
const ADD_OBJECT= (state: State, action: featureAction.AddObject) => {
const obj = {...state.entities[action.payload.objId]};
obj.values= [...obj .values, ...[action.payload.newObj]];
return featureAdapter.updateOne({
id: action.payload.objId,
changes: obj ,
}, state);
};
but this is overkill as everything is renewedm can't I just update the array ?
Variable vals
here const vals= state.entities[action.payload.objId].values;
references to the object from State. So vals.concat(action.payload.newObj);
mutates that Object.
You should not mutate State.
And this const obj = {...state.entities[action.payload.objId]};
works because spreed creates a new Object (a new reference). Then NgRx will capture reference change and update the State.