Managing async operations states in Vue components
This article describes how to make the management of async operations states easier and don’t pollute component by ancillary code that doesn’t carry any payload.
Let’s imagine the fairly typical case when you have to have several async operations in one component. It can be a dashboard with several (e.g. three) widgets and each of them requires some data from a separate API endpoint.
Let’s assume we have the following requirements:
- you have to display a pre-loader inside of each widget
- you have to display a loading message for an entire dashboard
- you have to display different loading messages (for an entire dashboard) for the first time loading and for reloading data
- you have to display an error inside each widget if a request failed
- you have to display an error message for entire dashboard if at least one request failed
A typical implementation will look like this:
The approach above is absolutely clear and actually that’s most obvious and fastest way to achieve the result, that’s why it’s offered in some official resources e.g. here. Although this approach is popular it’s too verbose and has repetitive code without any payload, isn’t it?
- it’s only to serve data loading, so try to imagine how will it look when it will be mixed with some business-logic?
- how will it look if you’ll have to have more than three async operations?
- what if you need to have some more sophisticated grouping?
Developing Vue apps we face that almost daily, that’s why we have published “vue-async-operations” plugin which wraps your async operations taking care of states and provides the logical and clear way to access them.
Take a look at how the task above can be done using “vue-async-operations”:
With “vue-async-operations” you can trigger all operations at once or perform only some particular one. You can group operations any way you need. You’re free to handle states of each operation separately and have the reactive state for the whole batch at the same time. And finally, using all these opportunities you can easily keep your code cleaner and free of ancillary stuff mentioned above.
The plugin provides more abilities than shown in the scope of this article. Explore all the features and cases in the documentation at the Github.