Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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.

Good point, thanks.

1 Answer

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
      }),
    }))
  }