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
Published 7 years ago
Updated 6 years ago

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.

egghead
egghead

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today