JavaScript React Components Managing State and Data Flow Update State Based on a Player's Index

Michael Cook
Michael Cook
Full Stack JavaScript Techdegree Student 25,018 Points

My approach to updating score

As it says in the notes for this video, updating a player's score by changing state directly is not a good idea. Before I took any React courses I did the tutorial on the React website and it talks a lot about the importance of immutability: you don't want to change your data directly. Instead you want to replace the old state with a new state that reflects the desired changes. This is my handleScoreChange method:

  /**
   * Update a player's score
   * @param {Number} delta - change in score
   * @param {Number} i - index of player
   */
  handleScoreChange = (i, delta) => {
    this.setState((prevState) => ({
      score: prevState.players.map((player, index) => {
        if (i === index) {
          player.score += delta
          return player
        } else {
          return player
        }
      }),
    }))
  }

I just simply map over the previous state and update the score where the player object's index matches the index passed as an argument, else just return an identical copy of the object. Using map returns a new array, so it keeps your data immutable. In my opinion this is the easiest and most elegant way and I just wanted to share it.

Zimri Leijen
Zimri Leijen
9,629 Points

You can simplify it a little, it doesn't need the else block.

  handleScoreChange = (i, delta) => {
    this.setState((prevState) => ({
      score: prevState.players.map((player, index) => {
        if (i === index) {
          player.score += delta
          }
      return player
      }),
    }))
  }