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 React Component Patterns Refs and the DOM

Roderick Hung
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Roderick Hung
Front End Web Development Techdegree Graduate 23,182 Points

I 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
Sail Liao
6,654 Points

I 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
Steven Parker
231,269 Points

This code is using the post‍increment 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 pre‍increment 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Roderick Hung
Front End Web Development Techdegree Graduate 23,182 Points

Steven 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
Steven Parker
231,269 Points

Sharing 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.