This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Handle a rejected promise and display error to user using setState()

    Erik AybarErik Aybar

    In this lesson we will account for errors encountered during a failed requests and display a helpful error message to the user. We will add a catch() handler (Promise.prototype.catch) to our request's promise where we will add an error message to component state and set our loading state to false. We'll add an error message to our app that will only display once an error has occurred using conditional rendering.

    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 there's one new concept I want to introduce here, and that is I want to account for if we have an error, we want to make sure to display that to the user. If we have an error, we're going to pluck that out of state, we're going to display it right here for the user to see. In order to get an error to throw here, we're going to make our delete item request up here.

    00:24 We're going to say this is our fake request. That's going to fail for ID three specifically. What we're going to do here is, we will say if the ID is equal to three, the function we're going to pass the set time as is going to be reject, which will reject the promise. Otherwise, we'll resolve it as usual.

    00:45 As we can see for item one, item two, this is succeeding. If we click on item three, we have yet to handle that rejection. We're going to add for clarity here that we're beginning with null as error in our state, which is why we're not rendering anything quite yet.

    01:04 If we add a handler here on the promise through the catch, this is what we're going to do if the promise is rejected, we are going to set state error that request failed for item. Since we have the ID right here, I'll use that in the message. We can make sure this is happening as we expect.

    01:26 There we go. Now, if we click on item three, that we get our error message. Looks like we forget to clear out our loading state, let's go ahead and make sure that in any case that we set loading back to faults.

    01:42 Now, we'll go ahead, and item two will succeed, item three will fail. We're no longer loading, and we've displayed our error to the user...

    Discuss

    Discuss