kendy
kendy

Reputation: 179

How to make the data from Firestore in to a global variable?

How can I make the value return outside the onSnapshot function?

function checkIfExisting(){

  const collection = firebase.firestore().collection("audit");
  const getCaseID = collection.where("caseID", "==", "00001234");

  getCaseID.onSnapshot(function(querySnapshot) {
    let wordLists = [];
    querySnapshot.forEach(function(doc) {
    //get all the scanned words under "word" field in the Firestore Database
        wordLists.push(doc.data().word);
    });

    console.log("words: ", wordLists);// return a value

  });

  console.log("words1: ", wordLists);// undefined

  }

I knew that the console.log("words1: ", wordLists) is outside the function that's why I can't get its value. Could you please give me an idea on how can I call it outside the function (if possible).

Upvotes: 3

Views: 1231

Answers (2)

Peter Haddad
Peter Haddad

Reputation: 80914

To access it outside, you can use Promise:

function checkIfExisting(){
  return new Promise((resolve, reject) => {
   const collection = firebase.firestore().collection("audit");
   const getCaseID = collection.where("caseID", "==", "00001234");

   getCaseID.get().then(function(querySnapshot) {
     let wordLists = [];
     querySnapshot.forEach(function(doc) {
     //get all the scanned words under "word" field in the Firestore Database
        wordLists.push(doc.data().word);
          resolve(wordLists);
     });
     console.log("words: ", wordLists);// return a value
  });

Then to access outside do the following:

checkIfExisting().then((result) => {
   console.log(result);
});

result will contain the wordLists

Check the following for more information:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Upvotes: 3

panepeter
panepeter

Reputation: 4242

Your variable wordLists is defined (by using let) inside the callback (function) passed to onSnapshot. Even ignoring the fact that that's an asynchronous operation (which Peter's answer tackles using a Promise) – you cannot access a variable defined inside a function outside of that function.

You can learn about variable scoping here on SO, quick n dirty – or in Kyle's excellent you don't know JavaScript series, which is available freely on github or in print. Part 2, Scope & Closures. Also, to actually understand Peter's answer, Async & Performance.

Upvotes: 0

Related Questions