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

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

Added a bit of code to update the id when players are added/deleted. Is this okay?

In the video, I didn't really like how Guil set up how to add new player id's so I played around and found that I could update the id's of the players each time a player is added/deleted.

  handleAddPlayer = (name) => {
    this.setState((prevState) => {
      const updatedPlayers = [...prevState.players];
      updatedPlayers.map((player, index) => {
        return (player.id = index);
      });

      return {
        players: [
          //adds in all the previous players
          ...prevState.players,
          {
            name,
            score: 0,
            id: updatedPlayers.length,
          },
        ],
      };
    });
  };

Every time someone is added or deleted, it maps through the previous state and updates the id based on its index. I know this is somewhat trivial, but I just wanted to know if doing something like this is a problem?

Steven Parker
Steven Parker
229,732 Points

I was going to compare this to the original code, but you forgot to include a link to the course page this is based on.

2 Answers

Steven Parker
Steven Parker
229,732 Points

Without comparing the functionality of this code to the original, two things caught my attention:

Typically, "map" is used to create a different array without changing the original, and assigning that new array to a variable. For a case like this where the original is being changed and no new variable is being created, a "forEach" method would be commonly used instead of "map".

And the concept of changing existing id values is also unconventional. Depending on how they are being used elsewhere in the code, this may or may not create an issue; but it's a far more common practice to preserve an identifier assigned during creation for the life of an object.