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.


    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.



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

    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.

    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.

    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.

    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.

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