Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,676 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!