Loading indicators

Mike Kucherov
4 min readMay 13, 2022

--

In this little story I’d want to talk about loading indicators or preloaders. I’m not going deep into the creating of such indicators or its UX implementations. I’ll use default spinner from Angular Material.

Let’s say we have a sample app with button that adds a card to the list. But adding isn’t happening instantly. Imagine we need some time to send request to the database to update our list. Since this process is asynchronous if the user will click Add card button two or three times we’ll have something like this.

Database doesn’t know that card is created when user clicks button second and third time, so it gives cards the same id number. Well that’s not something we’d like to see in our app. To prevent such behavior we could disable button while request is in progress. And to let user know that we’re working on his request we need to display some indicator.

The easiest and most common way of doing so is to add isLoading variable and change its value to true on button click. Then set it back to false when our request returned from the server.

And the script will look something like this:

Note that we’re turn isLoading to false both for resolve and reject of our request!

Now user is unable to click the button until request is resolved. Sweet!

That approach is 100% legit and there’s nothing wrong with it. But after n-th usage of this technique I started thinking to myself that creating isLoading flag variable for every spinner I need is a bit dull. So I decided to move this logic to the global scope of the app.

Basically what I wanted to do is create a global object that will hold current loading entity key or null if nothing is loading at the moment.

At this point of time if you’re not using TypeScript I highly recommend you to start doing so. Because enum will save us from misspelling the loading key in our code. But you can also type this key yourself instead of using enum.

The only thing missing is handling these keys in our template.

We’ve also utilize Angular ng-templates to reuse indicator element

Notice that we can keep in that indicator variable not only enum keys but also any other key. For example we don’t need to display loading spinner on every delete button, while we deleting only one card. We’re just passing card id as a key to the indicator and checking if this specific card deletion button is connected with the button with the same id.

I intentionally tried to keep this article framework agnostic and avoid concrete implementation description. Because you could use this approach however you want. If you’re an Angular developer you’d put this indicator in the root service. Or maybe you need such indicator for every component in your React project. These are just my way of working with loading indicators which was evolved into this state through the years of software development.

--

--