Incorporating role-specific paths in Vue Router using Pinia

Is it possible to load one of three potential routes based on a user's role in my pinia store? The issue I'm currently facing is that the pinia store doesn't appear to be initialized before the router is set, resulting in the error

Uncaught Error: [🍍]: getActivePinia was called with no active

How can I resolve this problem?

Just as a point of reference, here are how the routes are defined:

const roleOneRoutes = [
  {
    path: '/home',
    name: 'home',
    component: () => import('@/pages/RoleOne/Home'),
  },
  ...
]

const roleTwoRoutes = [
  {
    path: '/home',
    name: 'home',
    component: () => import('@/pages/RoleTwo/Home'),
  },
  ...
]

Ideally, I would like something similar to the following in the index file:

const { user } = useAuthStore()

const mappedRoutes = user.role === 'roleOne' ? roleOneRoutes : roleTwoRoutes

export const router = createRouter({
  history: createWebHistory(),
  routes: mappedRoutes
})

Answer №1

Pinia store is not accessible at the top of a module in the usual way. The function useAuthStore is used instead of an object to prevent eager access. It should be called only when the store data is actually required, as accessing it prematurely could lead to a race condition, especially if the user data is not yet set.

A view component can be conditionally set up like this:

  {
    path: '/home',
    name: 'home',
    component: () => useAuthStore().user.role === 'roleOne' 
      ? import('@/pages/RoleOne/Home')
      : import('@/pages/RoleTwo/Home')
  },

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

Prevent the hiding of a select element with jQuery Chosen Select

I am facing difficulty hiding a select element with the chosen-select class if it does not have any elements present. I attempted: $("#Category2").hide(); and also tried removing the chosen-select class before hiding the element: $("#Category2").re ...

Managing browser back button functionality

I've been struggling to find a solution for handling the browser back button event. I would like to prompt the user with a "confirm box" if they click on the browser back button. If they choose 'ok', I need to allow the back button action, ...

Issue with AJAX POST request: PHP failing to establish session

I would like to pass the element's id to PHP and create a session for it. This snippet is from a PHP file: <?php $sql = "SELECT id FROM products"; $result = mysqli_query($con,$sql); while($row = mysqli_fetch_array($result)) { ?> <tr cl ...

Comparing AngularJS and AppML

As a beginner in AngularJS and AppML, I am curious to understand the strengths and differences between these two frameworks. Despite some similarities I noticed on W3Schools, I'm eager to dive deeper into each one's unique features. ...

Click on the button to automatically scroll to a specific component inside the dialog

In my JSF/Primefaces application, I have a page with a long content that can be scrolled, along with a dialog also containing lengthy content that requires scrolling. The dialog includes a button and I am looking to scroll the dialog content to a specific ...

What is the best method for starting a string using the symbol '~'?

Hello everyone! I have a task that requires me to add a special feature. The user needs to enter something in a field, and if it starts with the tilde (~), all subsequent entries should be enclosed in a frame within the same field or displayed in a list ...

What is the procedure for utilizing Javascript to redirect a user on a website back to the login page if necessary?

Is there a way to redirect a website user back to the login page if they try to access a secure page without logging in first? I'm looking to implement this using JavaScript and cookies. Any suggestions or ideas on how to achieve this seamlessly for t ...

Vue looping through an object containing arrays

I am facing an issue with my code where I need to iterate over multiple objects with arrays, but no return data is being displayed. Can someone please help me with my code? Here is a sample of JSON data retrieved from an API: "sections": [ ...

Executing a pair of queries within the same table and integrating them within a unified route

How can I efficiently execute two queries on the same table in my project? I have been considering using promises, but my knowledge on them is limited. Even though I've researched about it, I am struggling to implement the correct structure. My main ...

Encountering a 503 Error in Loading .js Files from Index.html in a .NET 7.0 Angular Application

I recently came into possession of an Angular project that I am trying to set up in IIS, but I am encountering some unusual behavior. Since I am relatively new to Angular, I ask for your patience as I navigate through this issue. Upon loading the website, ...

Unable to send message using window.parent.postMessage when src is set to "data:text/html;charset=utf-8" within an iframe

I'm currently working on a project to develop a compact editor that allows users to edit HTML using an iframe. I'm passing an HTML string into the src attribute as data:text/html, but I'm encountering challenges with communication in the par ...

Using a temporary variable within a Vue loop

Currently, I am utilizing Vue along with Vuetify to create a menu containing links using the treeview component. The data source I'm working with is a nested JSON structure. The issue I am facing is regarding linking the parent "to" with its children ...

Are there any testing frameworks available for JavaScript that are similar to Junit and specifically designed for testing object-oriented JavaScript within Node

What are some recommended methods for testing object-oriented JavaScript in Node.js? For instance, let's consider the following Cat.js class: function Cat(age, name) { this.name = name || null; this.age = age || null; } Cat.prototype.getAge ...

Navigating the art of employing different fonts for a website

I am looking to incorporate the trainway font into my website, but I'm concerned that the user may not have it installed on their device. Is there a way to showcase text in a specific font without requiring the user to download and install it? Thank ...

Running and storing JavaScript in NEW Selenium IDE: A comprehensive guide

I am facing a challenge with updating my old test scripts that were originally created for the outdated Selenium IDE. The task at hand is to modify them to work with the latest version of Selenium, but I am struggling to make sense of how to handle section ...

Unable to retrieve the store's vuex state

Below is the main file path /main.js import Vue from 'vue'; import App from './App.vue'; import vuetify from './plugins/vuetify'; import router from './router'; import store from './store/index.js'; Vue.c ...

What causes the indexOf method to return -1 even when the values are present in the array?

Could someone explain why the indexOf() method returns -1 even though the values are present in the array? The includes() function also returns false for me. I feel like I must be missing something or forgetting a crucial detail. Any insights on why the ...

The browser is throwing errors because TypeScript is attempting to convert imports to requires during compilation

A dilemma I encountered: <script src="./Snake.js" type="text/javascript"></script> was added to my HTML file. I have a file named Snake.ts which I am compiling to JS using the below configuration: {target: "es6", module: "commonjs"} Howeve ...

"Trouble encountered when submitting data to an external system by writing the image source - issues with Firefox and

I've been diving deep into various online resources to find a solution for an issue I'm encountering. My familiarity with Javascript is limited, so please bear with me. Whenever I click on the next button during checkout, a script runs to submit ...

The JavaScript require() function appears to be malfunctioning

Why am I encountering an error when trying to import a valid node_module? <script > var Twit = require('twit'); </script> Error: Uncaught ReferenceError: require is not defined I am puzzled as to why the require() function wor ...