0

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?

supermar10
  • 130
  • 14
  • Does this answer your question? [Why can't I directly modify a component's state, really?](https://stackoverflow.com/questions/37755997/why-cant-i-directly-modify-a-components-state-really) – Ergis Sep 03 '21 at 08:04
  • 2
    @Ergis : I guess, `redux-toolkit` tag is worth attention here, since it has [Immer](https://immerjs.github.io/immer/) under the hood that _translates_ state mutations into immutable updates. – Yevhen Horbunkov Sep 03 '21 at 08:17
  • @YevgenGorbunkov Didn't know about that actually. So thanks for the notice :) – Ergis Sep 03 '21 at 10:44
  • As @YevgenGorbunkov rightly said, it's the immerjs tag that's important (I guess) – supermar10 Sep 06 '21 at 14:00

1 Answers1

0

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;
    });
supermar10
  • 130
  • 14