Steps for invoking the next() function within the beforeRouterEnter guard

I've been grappling with this issue for countless hours now. I'm currently using Vue3

My goal is to implement a beforeRouterEnter guard in order to check the user's role upon login and direct them to the appropriate route accordingly.

Once the user successfully logs in from the login page, the userRoleId is saved in the Vuex store, and they are redirected to the homepage. The homepage contains 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();
    });
  },

However, I keep encountering the 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.'

This error occurs when I am NOT logged in and reach the else block (as soon as the next() line is reached), or when I am logged in and within any true if statement, causing the redirect to malfunction.

Answer №1

A common error is using the next function within another next callback. By that time, the navigation process has already concluded, so instead of a redirection with router.push, this type of logic should be placed in the component's mounted method (the next callback executes after it) rather than in the router guard.

Incorporating unnecessary redirects is not recommended as the store is accessible globally and can be directly imported rather than being accessed through vm.

The correct approach should follow this pattern:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger an Ajax function using a button within a Bootstrap modal

I need to trigger an ajax function after selecting an option from a bootstrap confirmation modal. The modal will appear by calling the remove(parameter) function. Any assistance would be greatly appreciated function remove(parameter){ // $("#remove-mod ...

Troubleshooting problems with anchor-targets in Skrollr

I am experimenting with having divs overlap each other as the page is scrolled using Skrollr. Initially, I was able to achieve the desired effect with two divs. However, when trying to incorporate a third div, only the first and last ones seem to work prop ...

Vue app hosted on Firebase displays a blank page when user logs in

After deploying my Vue2 project to Firebase hosting server, visitors are required to log in to access the other pages. The issue is that once a user successfully logs in, they are redirected to the next page but it appears blank. Below is what the firebas ...

Shiny silver finish using three.js technology

I have recently started exploring three.js and am attempting to replicate a cube that looks like this: https://i.sstatic.net/CO9Eq.jpg One aspect I'm struggling with is creating the material for my cube. The material appears to be a silver polished fi ...

Navigating through different components in React is made possible with React Router

I have views in my application that depend on each other. For example, in one view a user can choose an item from a list (generated on the server), and in the next view they can perform operations on that selected item. The item is passed to the second v ...

What is the best way to call a JavaScript function within a PHP echo statement that outputs a <div> element?

Having trouble echoing this PHP code due to issues with single quotes, causing the HTML to end prematurely. Any suggestions on how to fix this? function button($conn){ $sql = "SELECT * FROM table"; $result= mysqli_query($conn, $sql); while($r ...

How can I utilize npm with the original source code instead of minified or bundled code?

I am looking to access npm and JavaScript (or TypeScript) 3rd party libraries directly from the source code. Similar to how I can make changes in Python libraries by going into their source code, I want to have the same capability with my JavaScript depen ...

Dealing with Class and Instance Problems in Mocha / Sinon Unit Testing for JavaScript

Currently, I am working on unit testing an express middleware that relies on custom classes I have developed. Middleware.js const MyClass = require('../../lib/MyClass'); const myClassInstance = new MyClass(); function someMiddleware(req, ...

Error message encountered: When attempting to execute 'postMessage' on a 'Worker', the operation failed as the object of type 'Array' could not be cloned

We are currently in the process of transitioning our code base from Vue 2 to Vue 3. Most things are working smoothly with HERE maps, except for one hiccup involving the .addObject() event. Unfortunately, this event keeps failing and displays the error mess ...

What is the best way to change a byte array into an image using JavaScript?

I need assistance converting a byte array to an image using Javascript for frontend display. I have saved an image into a MySQL database as a blob, and it was first converted to a byte array before storage. When retrieving all table values using a JSON ar ...

When a new element is introduced, onmouseenter feature assigns a unique dynamic function variable

I am incorporating elements generated by Javascript using a for loop. My goal is to pass different variables to a function for each element. Check out my code snippet: var thumbnail_box = document.createElement("div"); thumbnail_box.onmouseenter = functi ...

Characteristics of JSON data containing quotation marks within the property values

Is it possible to include JavaScript functions in JSON like the example below? My JSON library is struggling to process this structure because of the quotations. How can I address this issue? I specifically need to store JavaScript functions within my JSON ...

Exploring the array push method in ES6 destructuring

Is it possible to use something similar to the destructing assignment feature in ES6 to write cleaner code when pushing items into an array? I'm unsure how to implement it properly, especially within a context like Vue.js. Here is an example code snip ...

Unlocking the potential of Three.js with mouse picking

I am looking to implement object picking in the following code snippet: var Three = new function () { this.scene = new THREE.Scene() this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000) this.camera.po ...

Update the X-axis settings in Highcharts

Is it possible to pass an array from a PHP code to Highcharts? In the following PHP code, I create 4 arrays: TMax ($rows), TMin ($rows1), Rain ($rows2) for data and another one for days of consultation ($dia). $sth = mysqli_query($con,"SELEC ...

In the dragstart event handler, event.dataTransfer and event.originalEvent will consistently be null

I have been working on developing drag and drop directives for angularJS by referencing this informative post: However, I am facing an issue where the dataTransfer and originalEvent are consistently null within the dragstart event handler, preventing me f ...

"Encountering a problem with a missing object in jQuery when referencing

I'm encountering an issue with jQuery's $(this) object that's causing me to lose track of the this element in my code: $('.star').click(function (){ var id = $(this).parent().attr('id').split('rating')[ ...

Leveraging data within Gatsby to dynamically generate and display content

I am encountering a problem as a newcomer to Gatsby. In my EventsContainer, I have an UpcomingEvent component where I need to render specific data only when upcomingEvent is true. While I successfully utilized map for EventCard, I'm struggling to do t ...

Unable to retrieve information from the json-server

For my current project in Backbone.js, I'm utilizing the json-server package to populate it with data. I've created a db.json file containing the data and executed the command json-server --watch db.json. The server started successfully and is ru ...

Unveiling the Mystery: How Browser Thwarts Server Push in HTTP/2.0

After studying the documentation of HTTP/2.0, I discovered that it is feasible to completely close a referenced stream using the RST_STREAM frame. Check it out here: ()! I am curious about how this feature can be implemented in popular web browsers such a ...