1

I want to fetch data (a particular field in a doc) from Firebase FireStore → Assign that value to global variable → console.log that value.

My Research till now:

  1. I tried assigning the value to global variable → NOT WORKING
  2. I tried returning the fetched value

var a = firestore.collection("collection1").doc("doc1").get().then(){ return doc.data().FIELD}

  1. removing the return keyword from the above

Currently I am doing nested code like console.log() inside the then().

What my code looks like now

var a = "BEFORE";
console.log(a); // BEFORE
firestore.collection("collection1").doc("doc1").then(
  function(doc) {
    const myData = doc.data();
    a = myData.Reciept_Series;
    console.log(a); // DESIRED_VALUE
  }
)
console.log(a); //BEFORE

How can I make a = DESIRED_VALUE ie. How can I use the value that I got from FireStore .

Thanks in advance.

  • The problem is not **where** you access the value, but **when** you access it. The `console.log(a);` outside of the callback runs **before** the `a = myData.Reciept_Series;` has run, and there.s no way to delay it. See https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron and https://stackoverflow.com/questions/59068260/how-to-make-the-data-from-firestore-in-to-a-global-variable – Frank van Puffelen May 14 '21 at 14:30

1 Answers1

2

In the following code, the handler is called as soon as the Firebase returns your data

function handler(a) {
  // here you can work with a
}

firestore.collection("collection1").doc("doc1")
.then(doc => doc.data)
.then(myData => myData.Reciept_Series)
.then(handler)
.catch(console.error); // to debug: make sure the error (if any) is always reported

If you want to wait for the data, use async/await pattern:

(async function() {
  var a = await firestore.collection("collection1").doc("doc1")
    .then(doc => doc.data)
    .then(myData => myData.Reciept_Series)
  // here you can work with a
})();

Keep in mind that the Promise (returned by then()) is run asynchronously, so your code is not executed in top-down order, but as another task.

You can call await on top level just in modules, otherwise the main thread would be blocked by it. See the support table at the bottom of the linked page.

Your global variable is assigned, but asynchronously. Give the code some time and then click the following button:

<button onclick="console.log(a)">Log data</button>
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169