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 (2018) Managing State and Data Flow Adding Items to State

Juan Mendiola
Juan Mendiola
20,751 Points

Confused with the handleAddPlayer method

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

I need help understanding how this method works.

2 Answers

Jason Pallone
Jason Pallone
11,340 Points

So here we are setting the state of our app, specifically the players array. we start by creating a new array, cloning the players array into our new array using the spread operator( aka the ...) then we create a new object inside the new array. Name is the name of our argument for the function, sense we want name to be the property name in our new object and name will be the value of that name property, we can use ES6 for name, and just type name, which is equivalent to name: name. (Sorry if that's confusing I said name about 29 times! Feel free to ask for clarification).. We set the score property to 0, we set the id property to add 1 each time a new object is added via this function. So that way each new object has its own unique id. Then console log at the end will log to the console the newly created array.

I hope this helps! If you need any additional help or clarification please feel free to reach out!

Juan Mendiola
Juan Mendiola
20,751 Points

Thanks a lot! This really helped.