0👍
The problem is that there is race condition because dispatch
calls return promises that weren’t chained before accessing the result of their work.
A good practice is to chain every promise, unless proven other wise.
The code that created
contains actually belongs to the router in general because authentication logic is application-wide.
It’s unnecessary to access global dependencies on this
component instance. This is done for historical reasons because Vue originally was used in non-modular environment. In order to use outside components, global dependencies such as store
need to be explicitly imported. In case this cannot be done, this needs to be fixed.
In this case auth
instance is available through getInstance
. In case the authentication shouldn’t be done on each navigation, this needs to be done on condition, e.g.:
import { getInstance } from '.../auth';
import store from '.../store';
...
router.beforeEach(async (to, from, next) => {
const auth = getInstance();
if (...) {
...
await store.dispatch('loadToken')
await store.dispatch('getCompany')
...
next('/setup')
...
} else {
next()
}
})
getInstance
doesn’t serve a good purpose because it just exposes a variable. Instead, instance
could be exported and imported directly, the behaviour would be the same due to how ES modules work.
Also global store already holds application logic and commonly used to handle authentication, including local storage operations.