Having trouble with Vue and Vuex not returning the correct value in HTML?

I've implemented a navbar that displays specific menu items based on the user's role.

Below is the simplified HTML code for the navbar:

<v-speed-dial class="speed-dial-container contextual-text-menu" v-if="user && user.emailVerified" fixed top right
  direction="bottom" transition="slide-y-transition">
  
<v-icon v-if="checkAuthorization(['superAdmin', 'admin', 'pastor', 'member']) === true" class="mt-2"
    @click="sendComponent({ component: 'Dashboard' })">$admin</v-icon>
  
</v-speed-dial>

Here is my method:

async checkAuthorization(permissions) {
  if (permissions.length > 0) {
    const temp = await this.$store.dispatch('UserData/isAuthorized', permissions)
    return temp
  }
},

Vuex store setup:

isAuthorized({
  state
}, permissions) {
  const userRoles = state.roles
  if (permissions && userRoles) {
    const found = userRoles.some(r => permissions.includes(r))
    return found
  }
},

Even though all console logs display the correct values, the menu items in the HTML do not update accordingly.

For instance, after adding 'member' to

checkAuthorization(['superAdmin', 'admin', 'pastor', 'member']) === true
, and logging in with only the 'member' role, all console logs indicate true. Despite this, the expected menu item does not appear as intended.

Answer №1

It was mentioned in the comments that checkAuthorization is an asynchronous function and will return a Promise, so checking for promise === true is not valid.

In addition to that, I suggest changing isAuthorized to be a vuex getter instead of an action. For example:

getters: {
  // ...
  isAuthorized: (state) => (permissions) => {
    if (permissions && state.roles) {
      return state.roles.some(r => permissions.includes(r))
    }
    return false;
  }
}

Furthermore, update checkAuthorization to no longer return a promise like this:

function checkAuthorization(permissions) {
  if (permissions.length > 0) {
    return this.$store.getters.isAuthorized(permissions);
  }
  return false;
}

Answer №2

My typical practice :

I include a new user state labeled as Unknown and set it as the default state.

In my main.js (or main.ts) file, I trigger state.initialize(), which defines the user's state.

The crucial step is implementing navigation guards. Rather than checking routing guards on router-link (or URL or any other location at this stage), it is recommended to define them in the router itself. Utilize the router.beforeEach function to verify if the user has permission to access that route, and redirect them to a 401 page if necessary.

https://router.vuejs.org/guide/advanced/navigation-guards.html

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

Is there a way to load an image asynchronously when the page loads and show a loading gif during the loading process?

My image tag displays a dynamically generated graph from the database. The loading time can vary significantly, sometimes only taking a second while other times it may take up to 6 or 7 seconds for the graph image to appear. I am looking for a way to sho ...

Express.js application experiencing technical difficulties

When attempting to create a simple Express application with the file called serv.js, I encountered an error. Here is the code snippet I used: var express = require('express'), app = express(); app.listen(3000, function() { c ...

Presenting quiz questions using javascript

Currently, I am following the learning path on javascriptissexy.com and facing a challenge with displaying quiz questions in the best way possible. As a beginner student of JavaScript, my question is about how to approach developing the behavior of a quiz ...

The vue element el-select is not displaying the label based on the v-model

Utilizing el-select in VUE with element UI and employing objects as options. {id:'123',name:'label1'} Link id to value and name to label of options. Upon changing v-model to id '123', the 'label1' named option can& ...

Pause until the existence of document.body is confirmed

Recently, I developed a Chrome extension that runs before the page fully loads by setting the attribute "run_at": "document_start". One issue I encountered is that I need to insert a div tag into the body of the webpage as soon as it is created. However, a ...

Stuck on AMChart while trying to load data

Hello! I am currently utilizing the AMCharts framework to generate charts from data stored in a MySQL database. However, I have encountered an issue where instead of displaying the chart, I am stuck with a perpetual "Loading Data" message. You can view a ...

Can I link the accordion title to a different webpage?

Is it possible to turn the title of an accordion into a button without it looking like a button? Here is an image of the accordion title and some accompanying data. I want to be able to click on the text in the title to navigate to another page. I am worki ...

Proper method for incorporating loading and error messages with the help of useContext and react hooks

Currently, I have a context.js file that makes an ajax call and stores the data in an array to be shared across components. While adding some 'loading ...' text during the loading process using axios, I feel there might be a better way to handle ...

My JavaScript code is being executed before Chrome Auto-fill

I have successfully created form input elements in Chrome that display a floating label when focused. However, I am encountering an issue when the browser autofills the username and password fields with yellow prefilled text. The JavaScript for the float ...

Creating a text file while in a suspended state within the event handler on Windows 8 using HTML5

When the suspend event is triggered inside the winjs.application.oncheckpoint event handler, I am attempting to write a text file. The content of the file is my object in JSON format. Below is the code snippet: applicationData.localFolder.createFileAsync( ...

Nested V-If statements inside of a double V-For loop

As a newcomer to Vue, I am experimenting with running an IF statement inside two v-fors. My goal is to compare a value from one array of objects to a value of another array of objects and if true, render the value from the second array of objects. Here is ...

What is the method to modify the background color of el-pagination?

I am using el-pagination on a dark page and I want to make its background color transparent. When I do not use the 'background' prop, the background color of el-pagination is white. Here is how it looks: (sorry I can't add an image) htt ...

Limit the Datepicker in MUI (v5) to only accept two-digit years

I am currently using the MUI (v5) Datepicker for capturing user birthday information. The Datepicker has been localized to German language, resulting in the input format DD.MM.YYYY. However, many German users prefer using a shorter year format like DD.MM. ...

Tips for updating a reactive form with multiple layers of nested JSON values

I am tasked with retrieving and working with the data from a deeply nested (potentially infinite levels) reactive form that includes formArrays, formGroups, and formControls. This data is stored in a database. Currently, my approach involves patching the ...

What is the method for transmitting a message from localhost to a React frontend?

I am currently running a WebSocket server that is receiving streams of messages from an MQTT source. These messages are then sent to a localhost server on port 8080. The messages being received are actually a stream of random numbers. Below is the Python ...

What is the best way to invoke a function only once in typescript?

Struggling to implement TypeScript in React Native for fetching an API on screen load? I've been facing a tough time with it, especially when trying to call the function only once without using timeouts. Here's my current approach, but it's ...

The failure to build was due to the absence of the export of ParsedQs from express-serve-static-core

Encountered the error message [@types/express]-Type 'P' is not assignable to type 'ParamsArray'. Resolved it by installing specific packages "@types/express": "^4.17.8", "@types/express-serve-static-core": ...

Can you explain the purpose of the statement `var MyConstructor = function MyConstructor()`?

Can you explain the distinction between these two code snippets: var NodestrapGenerator = module.exports = function NodestrapGenerator() { yeoman.generators.Base.apply(this, arguments); // more code here }; and: var NodestrapGenerator = module.expor ...

Steps for storing an image file using Vue JS and my token

I have encountered a challenge while trying to upload an image to my API. The validation needs to remain on the page even after users have logged in. While the upload process functions properly through Postman, I am facing issues when attempting to execute ...

Using dynamic jquery to target specific elements. How can we apply jquery to selected elements only?

Hello everyone! I have been working on a simple hover color change effect using jQuery, but I noticed that I am repeating the code for different buttons and service icons. Is there a way to achieve the same result so that when a button is hovered, the co ...