Reputation: 783
I'm tring to load data from a particular user and push that data to specific input field. The path in Firebase is located at:
var query = db.ref('Clients/'+ clientName +'/form/');
I fecth data in the mounted()
lifecycle hooks as follows:
mounted(){
// Grab current user logged in from Firebase
var user = firebaseApp.auth().currentUser;
if ( user ){
// Grab displayName to use in path to retrieve that client's data
var clientName = firebaseApp.auth().currentUser.displayName;
// The path to that specific's client data
var query = db.ref('Clients/'+ clientName+'/form/');
query.once('value')
.then((snapshot) => {
// Get the client's location from Firebase and assign to clientLocation data in the DOM
this.clientLocation = snapshot.child('clientLocation').val();
});
}
}
When I make changes and SAVE MY CODE WITHOUT RELOADING the data gets pushed properly. However on reload I get the following error:
Error in mounted hook: "TypeError: Cannot read property 'displayName' of null"
I played around with all the lifecyle hooks:
But the data doesn't display. As it seems that the firebaseApp isn't "loaded" yet so I cannot fetch the "displayName" property value and thus cannot populate the path to the data.
How/when should I load this code that works but seems to run too early?
Upvotes: 1
Views: 979
Reputation: 598847
User information may need to be loaded/refreshed asynchronously. For this reason, always use an auth state listener to ensure your code runs when the user is available. Modified from the linked docs:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// Grab displayName to use in path to retrieve that client's data
var clientName = firebaseApp.auth().currentUser.displayName;
// The path to that specific's client data
var query = db.ref('Clients/'+ clientName+'/form/');
var that = this;
query.once('value').then((snapshot) => {
// Get the client's location from Firebase and assign to clientLocation data in the DOM
that.clientLocation = snapshot.child('clientLocation').val();
});
}
});
You could put this in mounted()
, but it should also work in any other lifecycle method.
Upvotes: 2