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

Balazs Peak
Balazs Peak
46,076 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
    );
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;
       })
      } 
      });

  }