Revert State On Request Failure using React setState and Closures

Erik Aybar
InstructorErik Aybar
Share this video with your friends

Social Share Links

Send Tweet

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.

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.