Javascript - Firebase Value To Global Variable
Solution 1:
Storing the value in a global variable is not a problem, it's the when that is messing you up.
Data is loaded from Firebase asynchronously. This means that code doesn't run in the order that you probably expected. You can most easily see this by putting some logging in there:
console.log("Before starting to load value");
ref.child("path").on("value", snapshot => {
console.log("Loaded value");
});
console.log("After starting to load value");
When you run this code it prints:
Before starting to load value
After starting to load value
Loaded value
That is probably not the order you expected. But it explains perfectly why the global variable is not set when you access it: the value hasn't come back from the database yet.
That's why you'll want to move the code that needs the data from the database inside the callback function. Alternatively you can use the fact that once()
returns a promise, which makes it easier to deal with as a result:
functionloadData() {
return ref.child("path").once("value");
});
loadData().then((snapshot) => {
... use the data from snapshot
});
Note that is asynchronous loading is an incredibly common source of confusion for developers who are new to it. I highly recommend checking out some of the other questions on the topic:
Solution 2:
I figured out a solution using jQuery
ref.child("path").on("value", snapshot => {
var y = Object.keys(snapshot.val())[2];
z = snapshot.val()[y];
$("#id").attr("data-stored", z);
updateVal();
});
var x;
functionupdateVal() {
x = parseFloat($("#id").attr("data-stored"));
}
console.log("It Works! " + x);
Post a Comment for "Javascript - Firebase Value To Global Variable"