Reputation: 129
I am trying to make a query to a firebase database using ionic. I want to store the the object snapshot.val() in a variable with the objective of displaying its content in my HTML code but I´m struggling with the scope of my upcomingOrders variable.
How can I update my variable inside the callback?
onFetchMyUpcomingOrders(){
var upcomingOrders = {}
const userId = this.authService.getActiveUser().uid;
var ref = firebase.database().ref("orders/confirmed");
ref.orderByChild("client/clientId").equalTo(userId).once("value", (snapshot) => {
upcomingOrders= snapshot.val()
console.log(upcomingOrders)
});
console.log(upcomingOrders) // Empty object, should contain snapshot.val()
}
It seems like it's updating by value. How can I update it by reference?
Upvotes: 2
Views: 789
Reputation: 598951
The data is loaded from Firebase asynchronously. While the data is being loaded, the function continues to run. When your console.log()
just before the end of the function executes, the data hasn't been loaded yet. Then when the data becomes available, your callback function is invoked.
So: your upcomingOrders
variable is being set correctly, just not at the moment where you currently want it.
To make this code work, you must move all code that needs the data into the callback function. So if you want to update the HTML, you do that from inside the callback:
onFetchMyUpcomingOrders(){
var upcomingOrders = {}
const userId = this.authService.getActiveUser().uid;
var ref = firebase.database().ref("orders/confirmed");
ref.orderByChild("client/clientId").equalTo(userId).once("value", (snapshot) => {
upcomingOrders= snapshot.val()
// TODO: update HTML and do whatever else needs the data
});
}
This is an extremely common pattern when using modern web APIs. Data is loaded asynchronously all the time, and callback such as this (or a more modern equivalent such as Promise
or async
/await
) are the only way to deal with it.
Upvotes: 1