Exploring the power of Firebase with Vue Js lifecycle methods

I am attempting to retrieve data from a specific user in Firebase and push that data into designated input fields. The path in Firebase is located here:

var query = db.ref('Clients/'+ clientName +'/form/');

I retrieve the data in the mounted() lifecycle hook as shown below:

mounted(){

// Retrieve current logged-in user from Firebase
var user = firebaseApp.auth().currentUser;

if ( user ){
 // Get displayName to use in path for retrieving the client's data
 var clientName = firebaseApp.auth().currentUser.displayName;

 // Path to the data of that particular client
 var query = db.ref('Clients/'+ clientName+'/form/');

   query.once('value')
     .then((snapshot) => {

        // Obtain the client's location from Firebase and assign it to the clientLocation data in the DOM
        this.clientLocation = snapshot.child('clientLocation').val();

     });
   }

}

After making changes and SAVING THE CODE WITHOUT RELOADING, the data is correctly pushed. However, upon reload, I encounter the following error message:

 Error in mounted hook: "TypeError: Cannot read property 'displayName' of null"

I have tried using all available lifecycle hooks:

  1. beforeCreate
  2. created
  3. beforeMount
  4. mounted
  5. beforeUpdate
  6. updated
  7. beforeDestroy
  8. destroyed

Unfortunately, the data does not appear. It seems that the firebaseApp is not fully "loaded" yet, preventing me from fetching the "displayName" property value and thus unable to populate the data path.

How and when should I execute this code so that it functions properly without running too early?

Answer №1

It is important to load/refresh user information asynchronously. To ensure that your code runs when the user is available, always utilize an auth state listener. The following code snippet is adapted from the linked documentation:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // Obtain displayName for use in data retrieval path specific to that client
    var clientName = firebaseApp.auth().currentUser.displayName;

    // Path to the client's data
    var query = db.ref('Clients/'+ clientName +'/form/');

    var that = this;
    query.once('value').then((snapshot) => {
       // Retrieve client's location from Firebase and assign it to clientLocation data in the DOM
       that.clientLocation = snapshot.child('clientLocation').val();
    });
  }
});

This code can be placed inside the mounted() lifecycle method or any other appropriate lifecycle method.

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

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

Find the identification number by searching through the text

I'm trying to find a way to retrieve the node id during a text search. Here's an example: http://jsfiddle.net/53cvtbv9/529/ I attempted using two methods to get the id of a node after the search: console.log($('#jstree').jstree(true). ...

Implementing $modal.open functionality in AngularJS controller using Ui-Bootstrap 0.10.0

Is there a way to properly call $modal.open from the controller in AngularJS since the removal of the dialog feature in ui-bootstrap 0.1.0? What is the alternative method available in the current version? In previous versions like 0.1.0, it was simply don ...

Using Three.js to transfer one object's rotation to another object

I have been attempting to transfer one object's rotation to another with no success using the following methods: //The first method rotates much faster than the original object's rotation boxme1.rotateOnAxis(new t.Vector3(0,1,0), cube.rotation.y ...

"Discovering the referring page URL in Next.js: A Step-by-Step

On a webpage, I use router.push('destination-url') to redirect users to an external link. I want to determine if the user has navigated back from the redirected page or not. If they arrived from an external link, they should not be allowed to re ...

What is the best way to eliminate the bottom border of an input field?

Seeking advice on how to eliminate the border-bottom of an input field when typing starts. .car-list-input { font-family: 'Source Sans Pro', sans-serif; border-radius: 3px; font-size: 14px; font-weight: 400 !important; height: 35px; ...

Gather data from various HTML elements with JavaScript when submitting a form

How can I extract values from HTML elements and send them for processing through a form? I'm attempting to compile a menu item list with the individual items' structure in place, but I'm struggling to figure out how to fetch the values upon ...

What is the reason behind Chrome's automatic scrolling to ensure the clicked element is fully contained?

Recently, I have observed that when performing ajax page updates (specifically appends to a block, like in "Show more comments" scenarios) Chrome seems to automatically scroll in order to keep the clicked element in view. What is causing this behavior? Wh ...

Check the length of a ngRepeat array after the initial filtering before applying limitTo for further refinement

Currently, I am implementing pagination in my Angular application by using a custom startAtIndex filter along with the limitTo filter. My goal is to show the total number of results in the dataset, regardless of the current page. However, due to the use of ...

Is there a way to prevent a link from activating when I click on one of its internal elements?

Within a div nested inside an "a" tag (specifically in Link within next.js), there is another div labeled as "like." When clicking anywhere within the main div, the intention is for it to redirect to the destination specified by the "a" tag. However, if th ...

What steps should I take to ensure that my website can recall the most recent interaction conducted by the user?

Our website features a search form that allows users to look for items on the page. In addition, there is a separate form with checkboxes that enables users to narrow down their searches in hopes of reducing the number of results returned. For example, i ...

Text in Angular vanishes upon reopening

I have a code snippet where I am trying to allow the user to edit and save a paragraph displayed on a side panel of the main page. Although the code works fine, allowing users to update the text and see it reflected in the network upon saving, there seems ...

react componentdidupdate triggers never-ending iteration

When I trigger an API call to elasticsearch using onChange, it prompts a list for autocomplete. To make sure that my store is updated before rerendering, I included componentDidMount so that I am not lagging behind by one tick. Here is the code snippet: c ...

Setting the locale in an extended datapipe in Angular 4: A step-by-step guide

I have created a custom pipe by extending the DataPipe Angular class. import { Pipe, PipeTransform } from '@angular/core'; import { DatePipe } from '@angular/common'; @Pipe({ name: 'dateTimeFormater' }) export class DateTi ...

Retrieve information from a form in AngularJS without relying on two-way data binding

Utilizing two-way data binding, the code operates effectively. However, there is a stipulation - instead of using =, use <. Upon the initial launch of the application, the text inputs will contain predefined values. The objective is to enable users to ...

Is there a way to determine if a user has the ability to navigate forward in Next.js?

I am faced with a challenge of determining whether a user can navigate forward on a webpage. My goal is to have two buttons - one to go back and another to go forward, with the forward button disabled when navigation is not possible. For the back button f ...

Failed verification of C-Lang in React-Hardware/Particle

Currently, I am utilizing React, React Hardware ([https://github.com/iamdustan/react-hardware/]), and Johnny-Five along with the Particle Photon. The error stack displayed below is what pops up when executing my lib/app.js file: # Fatal error in ../deps/v ...

Content not appearing in ng repeat loop

I'm facing a basic issue that I can't seem to solve - my code isn't working as expected: <article id="desktop"> <h3>Content: </h3> <ul> <li ng-repeat="x in storage"> name: {{x.name}} ...

File input onChange event not triggering after pressing SPACE or ENTER key

My React component features an img tag that allows users to select an image from their computer to display in it. While this component functions correctly on most browsers, I encountered an issue specifically with Chromium based browsers (tested on Chrome, ...

How come my data cannot be displayed using ajax?

Here is the code snippet: var xml=new String(""); //function to send data every 5 seconds window.setInterval(function() { //code to obtain xml file alert(xml);// when I try alert my variable xml contain data ...