JavaScript React Components Managing State and Data Flow Adding Items to State

Everton Carneiro
Everton Carneiro
15,993 Points

Every player must have a unique id or the ids must follow the number of players in the array?

I always like trying to build the code before see the teacher solution and in the case of handleAddPlayer method, I did like this:

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

This way, I make sure that the player id will be always the last item of the array. But seeing the teacher's solution, I notice that he did in a way that all players have a unique id, because if you delete two players before add one, the id will remain 5 for the added player. My question is: it`s a requirement that the players have unique ids in this case?

3 Answers

tomd
tomd
16,697 Points

I mean in the real world, yes. You want objects to have unique ID's. In databases id's auto-increment. If something gets deleted, another object doesn't take its place.

Removing a player is based on id so yes they need to be unique.

Jamie Gobeille
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jamie Gobeille
Full Stack JavaScript Techdegree Graduate 19,555 Points

Yes. In react, every object needs to have its own id or react will throw a warning. I believe it does this so the framework can differentiate and keep tabs on each item's state.

I wasn't a fan of Guil's solution for making the unique id so here is my solution! Each time a player is added to the array, the lastPlayerId variable will get the id of the last item in the array. Then when the id is set, it adds 1 to the id. This way the numbers don't increment in an odd manner and the id will always be unique.

  addPlayer = (name) => {
    let lastPlayerId = this.state.players.slice(-1)[0].id;
    this.setState({
      players: [
        ...this.state.players,
        {
          name,
          score: 0,
          id: (lastPlayerId += 1),
        },
      ],
    });
  };