Home > Blockchain >  How to call next() in the beforeRouterEnter guard
How to call next() in the beforeRouterEnter guard

Time:10-21

I have been stuck on this issue for hours now. I am using Vue3

I am trying to use a beforeRouterEnter guard to check what user role is currently signed in, and based on that re-direct the user to appropiate route.

After submitting the login form (From login page) the userRoleId is stored in the vuex, and i get re-directed to a homepage. The homepage has the following script:

beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (vm.$store.getters.userRoleId == USER) {
        next("/us");
        return;
      }
      if (vm.$store.getters.userRoleId == ADMIN) {
        next("/ad");
        return;
      }
      if (vm.$store.getters.userRoleId == SUPER_ADMIN) {;
        next("/sa");
        return;
      }
        next();
    });
  },

I keep getting following warning 'The "next" callback was called more than once in one navigation guard when going from "/" to "/". It should be called exactly one time in each navigation guard. This will fail in production.'

The error is there when: I am NOT LOGGED in and get moved to the else block (As soon as the next() line is reached), or when i am logged in and from inside whiever if statement is true as soon as next() is reached - causing the re-direct to not work.

CodePudding user response:

It's a mistake to call next inside next callback. The navigation has already been finished at that moment, this should have been a redirect with router.push instead, and this kind of logic belongs to component mounted (next callback runs after it) rather than router guard.

There should be no redirects here because they are unnecessary. A store is global and can be imported directly rather then accessed on vm.

It should be:

import store from '...';
...
beforeRouteEnter(to, from, next) {
  if (store.getters.userRoleId == USER) {
    next("/us");
  } else if ... {
    ...
  } else {
    next();
  }
},
  • Related