Ensure the computed variable is always up-to-date using Firebase in VueJS

After a successful sign-in through Firebase authentication, I need to update a navigation link.

The user login changes are managed within the created hook using .onAuthStateChanged()

 data () {
    return {
      user: null,
      additionaluserinfo: null,
      isAdmin: false
    }
  },
 created () {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.user = user
        
        // Fetching additional user information from Firebase
        db.collection('users').where('user_id', '==', user.uid)
          .get()
          .then((querySnapshot) => {
            querySnapshot.forEach((doc) => {
              console.log(doc.data())
              this.additionaluserinfo = doc.data()
              this.$store.dispatch('setAdditionalUserInfo', doc.data())
            })
          })
          .catch((error) => {
            console.log('Error getting documents: ', error)
          })

        this.additionaluserinfo = this.$store.state.additionaluserinfo
        
        // Checking user role for admin permissions
        if (this.$store.state.additionaluserinfo.role === 'admin' || this.$store.state.additionaluserinfo.role === 'superadmin') {
          this.isAdmin = true
        }
        
        // Checking user role for superadmin permissions
        if (this.$store.state.additionaluserinfo.role === 'superadmin') {
          this.isSuperAdmin = true
        }
      } else {
        this.user = null
        this.additionalUserInfo = null
      }
    })

I verify user rights in onAuthSateChanged.

The challenge lies in having to refresh the page for the navigation bar (v-if="isAdmin" / "isSuperAdmin") to reflect the updates. Is there a way to force an update within onAuthStateChanged?

Answer №1

Try either relocating the block of code:

this.additionaluserinfo = this.$store.state.additionaluserinfo
if (this.$store.state.additionaluserinfo.role === 'admin' || this.$store.state.additionaluserinfo.role === 'superadmin') {
  this.isAdmin = true
}
if (this.$store.state.additionaluserinfo.role === 'superadmin') {
  this.isSuperAdmin = true
}

within

this.$store.dispatch('setAdditionalUserInfo', doc.data()).then(() => { /* */ })
. Otherwise, the code may run before the data is properly stored in the state (asynchronous data fetching).

Alternatively, consider removing it altogether and implementing the following:

computed: {
    role: () => this.$store.state.additionaluserinfo ? this.$store.state.additionaluserinfo.role : '',
    isAdmin: () => this.role === 'admin' || this.role === 'superadmin',
    isSuperAdmin: () => this.role === 'superadmin',
}

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

Retrieve the parent element of the selected tag within an iframe

I have an embed iframe that displays an HTML page. Now I am trying to retrieve the class of the parent item that was clicked. <iframe src="//example.com" id="frame" ></iframe> This is the CSS styling for the iframe: #frame{ width:380px; he ...

I encountered an issue where my button's onClick function was not functioning properly with the clickable component

Here is my display I have a component(Product) that can be clicked. One of its children is also a button. However, when I click it, the Product's function runs. How can I make sure my button executes separately? <ProductForm> ...

Is it advisable to send a response in Express.js or not?

When working with Express.js 4.x, I'm unsure whether to return the response (or next function) or not. So, which is preferred: Option A: app.get('/url', (req, res) => { res.send(200, { message: 'ok' }); }); Or Option B: ...

What is the best way to utilize an AngularJS directive to send a POST request with all parameters from a form?

I have created a custom AngularJS form with Stripe integration using a directive. You can view the Fiddle for this project here: https://jsfiddle.net/u5h1uece/. HTML: <body ng-app="angularjs-starter"> <script src="https://js.stripe.com/v3/"> ...

The issue with Ionic 2 arises when attempting to use this.nav.push() because it

Recently transitioning from Ionic 1 to Ionic 2, I'm encountering an issue with using this.nav.push(nameOftheOtherPage) immediately after a promise. Interestingly, the function this.nav.push works fine when it's called outside of the promise funct ...

Problem with overlapping numbers in the Vis network

I am currently working on a project using Angular 8 and Visnetwork. Everything is going well, but I am facing an issue with overlapping numbers on lines. Is there a way to adjust the position of the numbers on one line without separating the lines? Can s ...

What is the best way to implement a delay when a user checks something in Vue.js?

I have a Single Page Application using Vue.js along with Laravel. The authorization logic is handled by Laravel app, but I need to check the authentication status when the routing changes. To address this, I created a small class for handling it. export d ...

The functionality of jQuery's appendTo method seems to be malfunctioning

I am trying to display an image with a popup using jQuery mobile. In my loop, I have the code below: for( var i = 0; i < imageArray.length; i++ ) { counter ++; // Create a new Image element var img = $('<img data-rel="popup" class=" ...

Angularfire not updating $scope value

I've encountered an issue with my code. The $scope value doesn't update after using $createUserWithEmailAndPassword. However, when I use alert($scope.message), the alert appears. What am I doing wrong? I have all the latest files from firebase a ...

How can I implement user-specific changes using Flask?

I am a beginner with Flask and I am working on a project where users can sign up, and if the admin clicks a button next to their name, the user's homepage will change. Below is the Flask code snippet: from flask import Flask, redirect, url_for, render ...

Combine two events in jQuery using the AND operator

Can I create a condition where two events are bound by an AND logic operator, requiring both to be active in order for a function to be called? Let's say you have something like this: foobar.bind("foo AND bar", barfunc); function barfunc(e) { al ...

Sending data from jQuery to an AngularJS function is a common task that can be accomplished in

In my Controller, I have a function that saves the ID of an SVG path into an array when a specific part of the image.svg is clicked. $(document).ready(function(){ var arrayCuerpo=[]; $('.SaveBody').on("click", function() { ...

Top solution for maintaining smooth navigation across web pages

As I dive into the world of web development, I find myself intrigued by the idea of reusing navigation and banners across multiple web pages. However, despite my research efforts, I have yet to come across a definitive answer. My objective is simple: The ...

Is it possible for me to invoke a div within a different component?

I am facing a challenge with a large div component. <div id='download> ..... </div> My goal is to incorporate this same component into a Paper within a Modal. <Modal> <Box sx={style} > <Paper elevation ...

Angular Authentication Functionality

I need to create a loggedIn method in the AuthService. This method should return a boolean indicating the user's status. It will be used for the CanActivate method. Here is a snippet of code from the AuthService: login(email: string, password: string) ...

Preventing the keyboard from showing on mobile devices when using a React date time picker

I am currently utilizing the React-date-picker component in my ReactJS application. I am encountering an issue where the keyboard is appearing along with the date picker when testing on mobile devices. I have attempted some solutions, but none have resol ...

An error was encountered stating "TypeError: Unable to call function on undefined object while attempting to utilize a JSON object

My current setup involves using D3js with MongoDB and AngularJS to showcase my data. Everything works smoothly until I decide to give my JSON array a name. Suddenly, Angular starts throwing errors at me and I'm left confused as to why. Here is the or ...

Resizing popups upon button activation

Hey there! I have a popup with a button that reveals random text containing between 0 to 32 words when clicked. The issue is, the popup keeps resizing based on the length of the text, causing the button to move around. Is there a way I can keep the button ...

Tips for preventing the "Error: Avoided redundant navigation to current location: "/inside/home" when the authentication guard restricts access to the route

Upon logging out, I would like Vue to automatically navigate to the default landing page. The current behavior is causing Vue to redirect to the existing route instead. This redirection gets intercepted by a guard that prevents it and sends the user back ...

Exploring creative methods for incorporating images in checkboxes with CSS or potentially JavaScript

Although it may seem like a basic question, I have never encountered this particular task before. My designer is requesting something similar to this design for checkboxes (positioned on the left side with grey for checked boxes and white for unchecked). ...