Reputation: 137
I am trying to store the text that I retrieve from my firebase database, but when I assign datasnapshot.val() to a variable, it seems to have no effect.
var ref = firebase.database().ref().child("Text");
var output = "initial";
ref.on('value',function(datasnapshot){
output = datasnapshot.val();
})
console.log(output);
The console.log still outputs "initial". Why is this?
Upvotes: 0
Views: 29
Reputation: 317372
Firebase APIs are asynchronous, meaning queries for data, (the on()
method in your case) will return immediately, and the results will be sent to you callback some time later. Your code is expecting to receive the results immediately, which will not happen. The log line is being executed immediately after the on()
method returns, before the results are available to the callback.
Instead of trying to use the results outside the callback, you should fully handle them inside the callback, where they first become available:
ref.on('value',function(datasnapshot){
output = datasnapshot.val();
console.log(output);
})
Please also read this blog post that goes into more detail about Firebase asynchronous APIs, and why they were designed like that.
Upvotes: 1