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

Check the data from the radio button selection

I am facing an issue with reading the values of radio buttons in a list, all of which have the same id. Despite trying to retrieve the value of each individual radio button, my code only reads the value of the first radio button. <script src="//ajax. ...

Issue encountered when attempting to utilize multiple datasets with Twitter Typeahead/Bloodhound

Hello, I am currently learning how to use Typeahead and Bloodhound with the latest javascript. Below is a snippet of my code: Html: <div id="multiple-datasets"> <input class="typeahead" type="text" placeholder="NBA and NHL teams"> </div ...

What are the steps to run a webpack project without relying on webpack-dev-server?

I've been working on hosting my project on GitHub pages by creating a /doc file and placing all my HTML, CSS, and JS there. If you're interested, you can check out my project here: https://github.com/mattfrancis888/the_movie_db The only way I&a ...

Steps to have index.html display when running the build command in a Svelte project:

Greetings everyone, I'm brand new to using Svelte and have a question that's been on my mind. I recently developed a small app in Svelte that works perfectly fine during development. However, when I run npm run build for production, the output ...

Newly included JavaScript file displays on view page, but triggers a 404 error when attempting to open

Once I implemented the following code in the child theme's function.php file: add_action('wp_enqueue_scripts', 'js_files'); function js_files() { wp_register_script('ajax_call_mkto', get_template_directory_uri() . ' ...

Creating expandable card components with React and CSS using accordion functionality

I am currently working on creating a card that will expand its blue footer when the "view details" link is clicked to show lorem text. However, I am encountering an issue where the blue bottom of the card does not expand along with the lorem text. You can ...

Similar to Angular ui-router 1.0.3, what is the equivalent function for reloadOn

After updating to UI-router v1.0.3 from v0.3.2, I noticed that the reloadOnSearch feature has been removed from the stateConfig. I'm having trouble finding the equivalent of reloadOnSearch in v1.0.3. It doesn't seem to be documented anywhere. A ...

Managing elements within another element in Angular

I am currently exploring the use of Component Based Architecture (CBA) within Angular. Here is the situation I am dealing with: I have implemented three components each with unique selectors. Now, in a 4th component, I am attempting to import these compon ...

Featuring a visual arrangement of categorized images with AngularJS for an interactive display

As I work on developing a web application with Angular, my goal is to create a grid layout that organizes items by category. Each row will represent a different category. Below is an example of the code structure I have in place: <ion-item ng-repeat="i ...

Ways to prevent prop changes from passing up the chain?

After some experimentation, I discovered that the props I passed to a component can actually be changed within the component and affect the parent. This behavior is discussed in the official documentation. While objects and arrays cannot be directly modi ...

Please execute the npm install command to install the readline-sync package in order to fix the error in node:internal/modules/c

Having trouble installing npm readline as it keeps showing errors, even after trying different solutions. Tried deleting folders and uninstalling nodejs but the issue persists. Need help fixing this problem. ...

CKeditor does not accept special characters or diacritics in keywords

Recently, I came across a helpful code snippet for CKeditor that counts and ranks the most used words in a textarea. This feature is invaluable for generating SEO-keywords suggestions while writing articles. However, there is an issue with non-English char ...

Blank Vue Page Generated by Laravel Mix

While attempting to run npm run dev or npm run production, I encountered an error stating that the Vue file did not have loaders defined. To resolve this issue, I turned to this helpful resource: Compillation problem of extensions in vuejs I made use o ...

navigating between html pages using sliding next and previous buttons

I am in the process of developing a multi-page form spread across 4 different pages. I would like to incorporate next and previous buttons to allow users to easily navigate through the form. Although I have tried looking online for solutions, most results ...

Node.js routing currently lacks the ability to easily verify the presence of a JWT token for every route

I have a node application where, upon routing to ('/login') with valid credentials, I generate a JWT token with an expiry time and direct the user to the next page. If the user tries to access any other route directly (e.g., '/home') af ...

Tips for improving the speed of loading infinite scroll pages

I am currently working on scraping over 100k rows from the provided URL. The data goes back approximately a month, loading in batches of 7-8 rows at a time. My current approach involves using a macro to scroll down the page slowly, which is effective but ...

The integration of socket.io with static file routing in node.js is encountering issues

I am currently developing a chat application and I have encountered an issue. When the static file routing is functioning correctly, the socket.io for the chat feature throws a "not found" error in the console. http://localhost/socket.io/?EIO=3&tran ...

The circular reference error in Typescript occurs when a class extends a value that is either undefined, not a constructor,

Let me begin by sharing some context: I am currently employed at a company where I have taken over the codebase. To better understand the issue, I decided to replicate it in a new nestjs project, which involves 4 entities (for demonstration purposes only). ...

Exploring Vue3/Vite Methodology

Could anyone please help me with implementing the "del" method in Vite? I am encountering an error with my current code: [Vue warn]: Unhandled error during execution of native event handler at <Home onVnodeUnmounted=fn ref=Ref< Proxy {…} > ...

What could be causing the custom delimiters in vuejs to fail to function properly?

I'm currently combining vuejs with Jekyll and I am looking to implement custom delimiters for vue since Jekyll uses the same ones. This is specifically for a static site setup. The versions I am using are vuejs v2.6.10, vuetify v2.0.0beta-4, and jeky ...