Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React by Example Building the Application Writing a Handler to Confirm Guests

Dor Sarel
Dor Sarel
9,987 Points

Can I change directly the specific guest?

Hi, In Guil`s solution he map over the array and find the relevant index and then change the property, and for the others he just return the object.

Can I change only the relevant guest without mapping over the rest like this:

toggleConfirmationAt = (indexToChange) => {
      this.state.guests[indexToChange].isConfirmed = !this.state.guests[indexToChange].isConfirmed;

Thank you!

1 Answer

That solution would work, but you shouldn't directly change the existing state values. Instead you could take a copy of the guests array and mutate the copy. You can then use setState to replace the existing guests array with your copy.

This is how I did it below.

const guestsArr = this.state.guests.slice();

guestsArr[i].isConfirmed = !guestsArr[i].isConfirmed;

this.setState({guests: guestsArr}); 

The React website has a tutorial which talks about immutability here