How To Make The Data From Firestore In To A Global Variable?
Solution 1:
To access it outside, you can use Promise
:
functioncheckIfExisting(){
returnnewPromise((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
Solution 2:
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.
Post a Comment for "How To Make The Data From Firestore In To A Global Variable?"