I have deeply nested data, and need to update some deeply nested child. Currently I do it by flatmapping the two upper level lists, then searching in all the possible tasks, and then mutating the task by calling the init function.
const tasks = state.data.flatMap((p) => p.hierarchyLines).flatMap((h) => h?.tasks);
const task = tasks.find((t) => t?.id === payload.id);
task?.init(payload);
task.init(data: any):
this.id = _data["id"];
this.start = _data["start"] ? new Date(_data["start"].toString()) : <any>undefined;
this.deadline = _data["deadline"] ? new Date(_data["deadline"].toString()) : <any>undefined;
...
This does not work, any advice on why it is not updating the state?
If anyone should ever run into a similiar issue. The problem was that immer does not handle classes well. https://immerjs.github.io/immer/complex-objects
For me the solution was copying the state first, then mutating it, and then returning the copy as described here: https://redux-toolkit.js.org/usage/immer-reducers#immer-usage-patterns
builder.addCase(fetch.fulfilled, (state, { payload }) => {
const stateCopy = _.cloneDeep(state);
stateCopy.loading = false;
const tasks = stateCopy.data.flatMap((p) => p.hierarchyLines).flatMap((h) => h?.tasks);
const task = tasks.find((t) => t?.id === payload.id);
task?.init(payload);
return stateCopy;
});