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 the Players State Based on Previous State

Tyler McDonald
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tyler McDonald
Full Stack JavaScript Techdegree Graduate 16,700 Points

Do we need to explicitly copy this.state instead of relying on prevState?

In a previous video when working on the handleChangeScore method, we were told to not only use prevState, but to also make an explicit copy of the state like this:

  handleChangeScore = (index, delta) => {
    this.setState((prevState) => {
      const copyOfPlayers = [...prevState.players];
      return { score: (copyOfPlayers[index].score += delta) };
    });
  };

Why are we not supposed to do this in the handleAddPlayer method?

1 Answer

Laura Coronel
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Laura Coronel
Treehouse Teacher

Hey Tyler McDonald! You are making a copy of the prevPlayers in the handleAddPlayer function! When you add the spread operator in front of the prevPlayers object you are bringing in a copy of that object to create a new player state object with the new player added to the bottom.

handleAddPlayer = (name) => {
  this.setState({
    players: [
      ...this.state.players,
      {
        name,
        score: 0,
        id: this.prevPlayerId += 1
      }
    ]
  });
}

Hope this helps!