1

My state model is like below

export interface State {
  [key: string]: UnitState;
}

So State is holding states of all units with key as unitID. So it should ideally look like this

{ 'ABC': {unitName: 'John', unitOpen: 'true'},
  'XYZ': {unitName: 'Peter', unitOpen: 'false'} 
}

Now when I want to do some state updates in the reducer how do I do that? I tried something like this but it didn't work. I checked other posts here, but none of them had examples for a key indexed array

case 'UPDATE_UNIT_NAME': {
        const stateCopy = Object.assign({}, state);
        const name = action.name;
        stateCopy[unitId] = { ...stateCopy[unitId], unitName: name};
        return {...state, stateCopy};
      }
code4fun
  • 31
  • 2
  • 3

1 Answers1

1

Issue

  1. Your state isn't an array, it's an object.
  2. You are copying your state, but then you nest the updated state in the next state object under a stateCopy property, which I am going to guess isn't the desired result you were after.

Solution

Shallow copy the state and also any nested properties that are being updated.

case 'UPDATE_UNIT_NAME': {
  const { name } = action;
  return {
    ...state, // <-- shallow copy state object
    [unitId]: {
      ...state[unitId], // <-- shallow copy nested unit object
      unitName: name // <-- update specific property
    },
  };
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181