Search code examples
javascriptreduxlit-elementlit-html

Lit-Element and Redux: Update Object in Array


I am trying to update the roll property in an object which is nested in the players array. My state looks like this:

players: [
  {
    "id": "44ufazeep0o",
    "name": "test-player-1",
    "roll": 0,
    "totalWins": 0
  },
  {
    "id": "eu8hutex7z9",
    "name": "test-player-2",
    "roll": 0,
    "totalWins": 0
  }
]

This is my action:

export const addRoll = (roll, id) => {
  return {
    type: ADD_ROLL,
    roll,
    id,
  }
}

This is my reducer:

case ADD_ROLL:
  return state.players.map((player) => {
    if (player.id === action.id) {
      return {
        ...player,
        roll: action.roll,
      }
    }
    return player;
  });
  ...

I am watching state.players in an components like so:

import { connect } from 'pwa-helpers'; // connects a Custom Element base class to the Redux store
...

stateChanged(state) {
   this.players = state.players;
}

render() {
  return html`${this.players.map((player)=> html`<h1>${player.name}</h1>`)}`
}

Now, whenever I call store.dispatch(addRoll(this.roll, this.id)), this.players.map() returns undefined in the component where I am watching state.players. Any input on why this might happen is much appreciated!


Solution

  • You have return an array instead of an object with players key in it from state after ADD_ROLL action is dispatched. Correct way to update it would be

    case ADD_ROLL:
      return {
        ...state,
        players: state.players.map((player) => {
          if (player.id === action.id) {
            return {
              ...player,
              roll: action.roll,
            }
          }
          return player;
        });
      }
      ...