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 Connecting the Confirm Guests Handler

Balazs Peak
Balazs Peak
46,160 Points

Guil updated state based on the previous state directly

Guil updated state based on the previous state directly. According to his teachings in the new course, this might cause state inconsistency, because React's setState is sometimes called asynchronously for performance reasons - this makes passing a callback function to the setState method a better solution compared to passing an object.

Reference: https://teamtreehouse.com/library/update-state-based-on-previous-state

I refactored toggleConfirmationAt() function by passing a callback to the setState, instead of an object.

  toggleConfirmationAt = indexToChange =>
    this.setState((prevState) => {
      return {
        guests: prevState.guests.map((guest, index) => {

          if (index === indexToChange) {
            return {
              name: guest.name,
              isConfirmed: !guest.isConfirmed
            };
          }

          return guest;

        } // map function callback function
        ) // map function call
      } // object returned by setState parameter callback function
    } // setState parameter callback function
    );

1 Answer

Saqib Ishfaq
Saqib Ishfaq
13,912 Points

definitely the right thing to do! i did the same>>>

  toggleConfirmationAt = indexToChange => {
      this.setState( (prevState) => {
       return {
         guests: prevState.guests.map( (guest,index) => {

         if(indexToChange === index){
           return {
           ...guest,
           isConfirmed : !guest.isConfirmed
         };
        }
        return guest;
       })
      } 
      });

  }