In this article we're using Vue 2. I can't guarantee that what's referred here is considered to be a good practice anymore, as I'm mostly involved with React these days.
Demo
Preface
Async - await is a killer feature introduced in ES7.
What I really don't like, is having to wrap everything in a try-catch block. The code seams really busy, and repeating it everytime for every async action is a no go.
Solution
Let's start by using a call that may or may not, resolve successfully.
Normally we would write something like this
Instead of that, we will wrap the request with another function which will handle any error.
What 'HandleError' can do practically depends totally on your needs.
For now, let's assume that we catch the error and generate the appropriate message for each case. We will dispatch an action that will populate some error messages and call it a day.
Vuex Setup
Our vuex setup will be the following:
Where the users module is as simple as that
As for the error handling actions, we will push the new error message in the state
And the custom toastr component will simply loop through every error message
Use a spinner
Sometimes though, we have to display a spinner. For this reason, I've made a separate module for the loading instance.
When a loader is needed, we won't call the action directly, but instead we'll dispatch 'executeWithLoader' with the action name as a param.