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 trialRoderick Hung
Front End Web Development Techdegree Graduate 23,182 PointsI can not get the player id to increment by one. Help please
'''javascript const handleAddPlayer = (name) => { setPlayers(prevPlayers => [ ...prevPlayers, { name, score: 0, id: nextPlayerId.current++ } ]); } '''
3 Answers
Sail Liao
6,654 PointsI think it's because the id is based on the output of setPlayers(). State updates are batched, so when you add players really fast, the newId would not change.
I move the increment out of the setPlayers() function by store the nextId into a variable:
const nextPlayerId = playerIdRef.current;
playerIdRef.current++
setPlayers(prevPlayers => [
...prevPlayers,
{
name,
score: 0,
id: nextPlayerId
}
]);
```JavaScript```
Steven Parker
231,198 PointsThis code is using the postincrement operator (nextPlayerId.current++
). While this does increment the value in the specified variable, the value of the expression itself is the current value, before the increment occurs.
There's also a preincrement operator (++nextPlayerId.current
) that increments the value first and then the expression itself returns the increased value. You might need to use that one instead.
Roderick Hung
Front End Web Development Techdegree Graduate 23,182 PointsSteven Parker, the video used nextPlayerId.current++ and was able to increment by one each time. My code is exactly the same but, does not increment by one after a player. How can I use nextPlayerId.current++ and increment by one each time?
Steven Parker
231,198 PointsSharing only code snippets can be problematic if the issue is actually being caused elsewhere in the code. When using a workspace, making a snapshot and posting the link to it here can help analysis greatly.