Reputation: 77
I am trying to pull data (the name of the user) down from firebase. I am able to pull the data down but I am not able to assign the data to anything out of firebase function. How am I supposed to get data out and use it? I want to simply update a label with the data I pull down.
getData(){
var userID = this.firAuth.auth.currentUser.uid;
var name;
console.log("userID: " + userID);
this.name = "user";
this.firService.database.ref("/users").once('value').then(function (snapshot){
snapshot.forEach(snap => {
if (snap.key == userID){
this.name = snap.val().name; //this wont work
}
});
});
}
Upvotes: 1
Views: 407
Reputation: 11326
That's because Firebase APIs are asynchronous. That means you can't get the data out. You'll need to use it inside the function.
Alternatively, you can use async/await from ECMAScript 2017. Declare your function as async
and use await
to retrieve the snapshot:
async function getData(){
var userID = this.firAuth.auth.currentUser.uid;
var name;
console.log("userID: " + userID);
this.name = "user";
var snapshot = await this.firService.database.ref("/users").once('value');
snapshot.forEach(snap => {
if (snap.key == userID){
this.name = snap.val().name;
}
});
}
Upvotes: 1