Using a global variable in Vue and noticing that it does not update computed variables?

Currently, I'm in the process of developing a web application and have begun implementing authentication using firebase. Successfully setting up the login interface, my next step is to propagate this data throughout the entire app.

Not utilizing Vuex, I attempted to establish a global variable by using Vue.prototype.$userData= {} to avoid the hassle of passing it down the components.

This code snippet initializes the variable in app.js:

  mounted() {
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        //RETAINING ADDITIONAL USER DATA HERE
        firebase
          .firestore()
          .collection('users')
          .doc(user.uid)
          .get()
          .then(function(doc) {
            if (doc.exists) {
              console.log(doc.data()) //THIS LOG WORKS
              Vue.prototype.$userData = {...user, ...doc.data()};
            } else {
              // doc.data() will be undefined in this case
              console.log('No such document!');
            }
          })
          .catch(function(error) {
            console.log('Error getting document:', error);
          });
      }
    });
  }

After that, an attempt was made to use it in a component as shown below:

  computed: {
    username: function () {
      if(this.$userData) {
        return this.$userData.naam;
      } else return "-";
    }
  }

Yet, the computed property does not seem to update once $userData finishes processing. Could there be an issue with how the global variable is being utilized?

P.S. Whenever modifications are made to the code resulting in a recompilation during npm run serve, the username displays correctly. However, upon refreshing the page, it fails to work again.

Answer №1

Try using the watch method instead of a computed property.

watch:{
  '$userData' = function(newValue){
     ...
     this.name = newValue.name;
     ...
  }
}

For more information, check out: https://flaviocopes.com/vue-watchers/

Note: Make sure you have access to the $userData variable throughout your Vue application.

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

I encountered login issues when trying to access dist/index.html in my Angular 8 application, but I found a workaround by utilizing the proxy.conf.json file, which

I have been trying to login through the index.html page in the angular 8 dist folder, but I keep encountering an error with the login API URL. Despite spending two days on this issue, I have not been able to find a solution. If anyone has any suggestions o ...

Utilizing Bootstrap and Javascript to efficiently handle multiple forms

My website uses Bootstrap for layout, and I need to submit a form that is duplicated for different screen sizes - one for large layouts and another for mobile. However, both forms go to the same endpoint, so I have to give them unique IDs. <div class=&q ...

Encountering issues with gulp-angular-templatecache while processing angular templates through pipelining

I've encountered an issue with gulp-angular-templatecache in my gulpfile. Here's the task causing trouble: gulp.task('templates', function() { return gulp.src(paths.angularTemplates) .pipe(templateCache()) ...

Creating a custom function in a Node.js application and rendering its output in the front-end interface

I've been trying to scrape data from a website and display it using innerHTML, but I'm running into some issues. The code snippet I'm using is: document.getElementById('results').innerHTML = searchJobs(''); However, I ke ...

Using MongoDB Object as middleware in Express applications

I’m facing issues trying to access the "DB" database object that gets created when the MongoDB client module establishes a connection with my MongoDB database. Currently, I am encountering an error indicating that in data.js, 'db' is not defin ...

Using a JavaScript variable inside a jQuery string

Does anyone have suggestions for what I may be doing incorrectly here? VIEW DEMO HTML Code <div id="usercurrentccbox"> <div class="cardChoice"> <label for="mastercard"></label> </div> </div> JQUERY Sc ...

Surprising non-synchronous operation within the computed property "vue/no-async-in-computed-properties" in Vue3

I am currently working on a Vue3 project and encountering an error when running it. Below is the complete code snippet that I am using. Can anyone assist me in resolving this issue? Thank you in advance. <script> import axios from 'axios'; ...

JQuery requests functioning flawlessly on one system while encountering issues on other systems

I've encountered an issue with the code on my admin page. It used to work perfectly fine on my system, but now it seems to have stopped functioning. My client urgently needs to update this page, however, when I attempt to run it, the JQuery requests a ...

Is jQuery Autocomplete functioning properly on outdated browsers, but not on newer ones?

Here is the JSON data I have for my auto complete feature { "list" : [ { "genericIndicatorId" : 100, "isActive" : false, "maxValue" : null, "minValue" : null, "modificationDate" : 1283904000000, "monotone" : 1, "name":"Abbau", ...

Leveraging async/await to handle the insertion of SQL data

function Scan_Insert_Recursive (dir_path) { //scans dir_path recursively and inserts file path into a temporary list Scan_Recursive(dir_path, (err, files) => { //using npm recursive_readdir for scanning if(err) { console.log(err) ...

Retrieving data from an external API using Express.js and displaying it on a website

I'm facing a challenge in handling a solution with node.js and express.js utilizing pug for rendering HTML. I need to render on a single page by retrieving values from separate HTTP GET requests from different websites. My goal is for express/node to ...

Is there a way to incorporate multiple functions into a single sx property, such as color, zIndex, backgroundColor, etc? Can this be achieved in any way?

I am currently developing a single search component that will be used across various sections of my application. Each component receives a prop called search: string to determine its type and apply specific styles accordingly. Although I could use classNam ...

What causes non-reactive variables to act unusual in Vue3?

Check out this code snippet: <template> <input type="button" value="click" @click="clickBtn"/> <div id="reactiveDiv">{{ reactiveVariable }}</div> <div id="noneReactiveDiv"&g ...

Tips for sending additional parameters to an MVC controller without including them in the URL when using the JavaScript window.open method

<a href="#" onclick="openAnchor('<%# DataBinder.Eval(Container.DataItem,"Url") %>', '<%# DataBinder.Eval(Container.DataItem,"infoToSend") %>')"> </a> openAnchor= function (Url, infoToSend) { window.open(Url, ...

Tips for integrating Typescript into a pre-existing Vue 3 project

The contents of my package.json file are as follows: { "name": "view", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve" ...

Can anyone help me figure out the best way to test for observable errors in Angular2?

I'm currently working on creating unit test cases for my Angular2 components. Up until now, the test cases have been running smoothly. However, I've run into some issues with my asynchronous calls. For example, I have a method for creating a n ...

Surprising Media Component Found in URL Parameters within the design

Exploring the page structure of my Next.js project: events/[eventId] Within the events directory, I have a layout that is shared between both the main events page and the individual event pages(events/[eventId]). The layout includes a simple video backgro ...

What is the reasoning behind the "open in a new tab" function triggering a GET request?

Check out this HTML tag: <a href="#" id="navBar_navBarInput_3_subNavDropdownInput_0_subNavLinkInput_0" onclick="redirectPost(4,'EntryData.aspx');">My Cool Link</a> The Javascript function "redirectPost" function redirectPost(id, ur ...

The $geoNear operator must be the initial stage in a pipeline to be valid

When performing an aggregation using nodejs as the server-side language, I encountered the error message $geoNear is only valid as the first stage in a pipeline. This is the Aggregation Object: [ { '$geoNear': { near: [Object], distanceFie ...

A guide on how to initiate a click event in Angular 5 using JQuery

I am trying to trigger a click event for each element based on its id, but it doesn't seem to be working. Below is the code I am using: ngOnInit() { this.getProductsLists(); } getProductsLists() { this.supplierService.getProductLists() .sub ...