reducer state update errors on array in typescript class with redux-toolkit

Viewed 43

I'm using redux-toolkit and need to update a state member after an frontend actions. The structure looks like that: state.theMap: { string: { string: ClassA } }. Something like:

{
  "keyA": { "keyAA": ClassA, "keyAB": ClassA },
  "keyB": { "keyBA": ClassA, "keyBB": ClassA },
  ...
}

So a map of another map with some typescript class (lets call it ClassA) and the end of it. ClassA has an array (arrayA) of string has a member: this.arrayA = ["a", "b", "c"]; for example.

First in the reducer I'm getting the good map and if I find it I call removeIndex on it.

changeContentOfMap: (state, action) => {
  const { firstKey, secondKey, indexToRemove } = action.payload;
  const classAInstance = get(state.theMap, [firstKey, secondKey]);
  if (classAInstance) {
    classAInstance.removeIndexes(indexToRemove);
  }
}

In ClassA, I have a removeIndexes method to remove stuff in the array. I'm using a lodash pullAt call: pullAt(this.arrayA, indexes).

Bear with me, this is of course oversimplified since I can't really share the real code. This works well if I'm doing it outside of reducers for the same values. But as soon, as I'm am in reducer, I get an error in pullAt, which is using a splice on the array: "Cannot delete property '0' of [object Array]". If I force and array copy before the pullAt: pullAt(...this.arrayA, indexes): no problem.

I'm sure it has something to do with immer which is use by redux-toolkit in the background. I've put this[immerable] = true; in my typescript class I even tried to do a produce function to see if that was the problem, something like:

  removeIndexesWithImmer = (indexes: string[]): void => {
    produce(this, (draft) => {
      return draft.removeIndexes(indexes);
    });
  };

But nothing really works, execpt recreating ClassA and cloning the array inside it. Which is not what I want to do.

I'm surely missing something. Any help would be appreciated.

Thanks.

0 Answers
Related