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 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;
      this.setState(this.state);
    }

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