sandrooco
sandrooco

Reputation: 8736

vue.js: Route guard wait for async value

As in every application I have a few routes. For example (router/index.js excerpt):

[{
    path: '/reporting',
    name: 'Reporting',
    component: reporting,
    meta: {
        adminOnly: true
    }
},
...]

As you can see in the route definition, when accessing reporting the user needs to have admin permissions, which is a property in a vuex store. The problem: This property is async and is of course false when initially accessing in the guard. How can I make my guard wait for it?

Guard:

if (to.matched.some(route => route.meta.adminOnly)) {
    if (store.getters.userInfo.isAdmin) {
        next()
    } else {
      next('/')
    }
} else {
    next()
}

Upvotes: 1

Views: 4337

Answers (1)

FitzFish
FitzFish

Reputation: 8629

What about watching the getter, using store.watch?

Assuming that your getter returns null if the data is not fetched yet.

if (store.getters.userInfo.isAdmin === null) {
    const watcher = store.watch(store.getters.userInfo.isAdmin, isAdmin => {
        watcher(); // stop watching
        if (isAdmin) next();
        else next('/');
    });
}
else if (store.getters.userInfo.isAdmin) next();
else next('/');

Upvotes: 5

Related Questions