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

Juan Mendiola
Juan Mendiola
18,602 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
9,482 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
18,602 Points

Thanks a lot! This really helped.