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 trialTyler McDonald
Full Stack JavaScript Techdegree Graduate 16,700 PointsDo 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
Treehouse TeacherHey 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!
Tyler McDonald
Full Stack JavaScript Techdegree Graduate 16,700 PointsTyler McDonald
Full Stack JavaScript Techdegree Graduate 16,700 PointsThat definitely helps. Thanks!