[英]Firebase and Vue Js lifecycle hooks
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:
Firebase中的路径位于:
var query = db.ref('Clients/'+ clientName +'/form/');
I fecth data in the mounted()
lifecycle hooks as follows: 我按以下方式在
mounted()
生命周期挂钩中影响数据:
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.
似乎firebaseApp尚未“加载”,所以我无法获取“ displayName”属性值,因此无法填充数据路径。
How/when should I load this code that works but seems to run too early? 我应该如何/何时加载此有效但似乎运行得太早的代码?
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. 您可以将其放在
mounted()
,但它也可以在其他任何生命周期方法中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.