Reputation: 27
I have an issue where I want to get a value from my Firestore database and store it to a variable. All this process should happen inside a function.
However, when I try to return the result and call the function I get undefined
in the console. But if I try console.log the value instead of returning I actually get the result that I want in the console?
I did my research and I found out that I have to do with asynchronous request. I read this particular answer https://stackoverflow.com/a/14220323/13540535 but I was not able to implement the solutions that Mr. Felix Kling told us.
How can I solve this and where in my code should I use async/await
?
First, here is my Firestore database:
And here is my code where I get undefined:
var userScore = 0;
var compScore = 0;
const userResult = document.getElementById("user-score");
const compResult = document.getElementById("computer-score");
const resultText = document.getElementById("pharagraph");
const rockButton = document.getElementById("r");
const paperButton = document.getElementById("p");
const scissorsButton = document.getElementById("s");
const joinButton = document.getElementById("joinid");
var firebaseConfig = {
MY FIRESTORE CONFIG..
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
function playerOne(){
db.collection("game").doc("8741").get().then((doc) => {
if (doc.exists) {
// here I get undefined
var p = doc.data().playerone;
return p;
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
})
.catch(function (error) {
console.log("Error getting document:", error);
});
}
var b = playerOne();
console.log(b);
Upvotes: 0
Views: 72
Reputation: 26333
Firestore documents are fetched asynchronously, so you'll need to either properly use Promises or use async/await
. Here's one way you could rewrite the code to properly handle async:
async function playerOne(){
const doc = await db.collection("game").doc("8741").get();
if (doc.exists) {
return doc.data().playerone
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}
playerOne().then(b => console.log(b));
Understanding async code and function closures is going to be very important to being able to successfully build JavaScript apps, so I'd recommend you do some more reading and experimenting there!
Upvotes: 1