Join egghead, unlock knowledge.

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
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    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.



    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




    Instructor: 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.

    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.

    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.

    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.