Add a loading indicator to UI for request in progress using setState()

Erik Aybar
InstructorErik Aybar
Share this video with your friends

Social Share Links

Send Tweet

In this lesson we will add state to our component to indicate whether we are loading to the user. We will "begin loading" before submitting our request to an API and then set "end loading" once the request is complete using Promise.prototype.then and setState(). This gives users a better experience than being left hanging wondering if their action of clicking the button had any effect. Now they will at least have some indication that work is being done while the request is in progress.

Instructor: [00:00] Just to illustrate this delay, let's go ahead, and we'll introduce a loading state. We'll fade out the entire list when we are loading. If we're loading, the style is going to equal. We're going to set some opacity here. Otherwise, if we're not loading, we'll set that to one.

[00:20] This needs to be an object with opacity property that we're setting. We've yet to introduce that state here, so we'll destructure that out of state along with our items. We'll set the default, and we'll begin as loading equals faults. What we're going to do here is, before we fire off the request, we're going to set state and we're going to set loading to true.

[00:47] Let's say immediately, we'll set that to true. When this is complete, after the request is complete, we'll set loading to false. Now, we have this fading in and out in between those requests.