Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Revert State On Request Failure using React setState and Closures

    Erik AybarErik Aybar

    A crucial part of implementing optimistic UI updates is properly handling failure cases. In the event of a request failing, we must revert the state which we’ve already updated since we assumed success at the time of user interaction. Thanks to the simplicity and power of setState() combined with Javascript's lexical scoping and closures, we can accomplish this relatively easily in React.

    reactReact
    ^16.0.0
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 We have our app rendering this list of tweets. When we click on this heart icon, what happens is that we immediately have made our state.

    00:09 We toggle the heart and increment or decrement this light counter. However, if we look at this failure case here, if we click on this heart, we update our state since we've assumed success but have yet to handle the failure.

    00:23 We need to do something more than just logging out to the console. Immediately on clicking the icon, we're invoking setState using our setState updater factory here, which accepts the tweet ID and the new liked status. We can reuse that right here in our error handler. Rather than toggling this as liked status, we can make use of the status it was at the time it was clicked.

    00:51 We can go ahead and restore it to that. Now if we click on this failure case, we'll see that it updates, and at the time it fails, it reverts.

    Discuss

    Discuss