-2

I'm using Redux with Immer. This is my code so far:

clearMachineState(state, { payload }: ClearMachineStatePayload) {
  const childrenIds = payload.children.map((child) => child.id);
  const newMachines = typedMachineState.machine_state.machines.flatMap((machine) => {
    const tmpMachines: MachineMapping[] = [];
    childrenIds.forEach((id) => {
      console.log(id, machine.machine_id);
      if (id !== machine.machine_id) {
        const foundMachine = tmpMachines.find(
          (tmpMachine) => tmpMachine.machine_id === machine.machine_id,
        );
        if (!foundMachine) {
          tmpMachines.push(machine);
        }
      }
    });
    console.log({ tmpMachines });
    return tmpMachines;
  });
  console.log({ newMachines });
  state.machine_state.machines = newMachines;
}

I want to remove from state.machine_state.machines, these machines, which are present in payload.children. The problem is, when I use the code above, in TS, all seems well, but when I log {tmpMachines}, I see this:

Object { tmpMachines: (1) […
tmpMachines: Array [ Proxy ]
0: Proxy { <target>: null, <handler>: null }
length: 1
<prototype>: Array []
<prototype>: Object { … }

But if I use the mocked array, like so:

const newMachines = typedMachineState.machine_state.machines.flatMap((machine) => {...

I get the actual object.

But either way, the state.machine_state.machines = newMachines; assignment doesn't happen. It does, if I try to do a state.machine_state.machines = [];, but not for my created arrays.

I'd also like to map on state, not on an external source.

What am I missing?

Alex Ironside
  • 4,658
  • 11
  • 59
  • 119

1 Answers1

0

This wasn't an immer problem. This was a logic problem. Here's the working code:

clearMachineState(state, { payload }: ClearMachineStatePayload) {
  const childrenIds = payload.children.map((child) => child.id);
  const newMachines: MachineMapping[] = [];
  typedMachineState.machine_state.machines.forEach((machine) => {
    if (!childrenIds.includes(machine.machine_id)) {
      newMachines.push(machine);
    }
  });
  state.machine_state.machines = newMachines;
},
Alex Ironside
  • 4,658
  • 11
  • 59
  • 119