0
ref.child("path").on("value", snapshot => {
  var z = Object.keys(snapshot.val())[2];
  y = snapshot.val()[z];

  //Call the friggin thing
  exportData(y);

  function exportData(y) {
    exporting(y);
  }
});

function exporting(y) {
  var x = y;
  //console.log(y);
  return x;
}

I want to store x in a global variable.

I cannot do code just below because 'y' will not be passed through. 'y' is a local variable.

var answer = exporting();
answer();

2 Answers 2

3

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:

function loadData() {
 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:

Sign up to request clarification or add additional context in comments.

Comments

0

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;
function updateVal() {
  x = parseFloat($("#id").attr("data-stored"));
}

console.log("It Works! " + x);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.