Gatsby
Gatsby

Reputation: 38

How can I set data from firestore to a global variable

I am trying to fetch data from firestore and set it to a global variable but I'm getting undefined. Here is what I have;

let myScore;

      auth.onAuthStateChanged((user) => {
        let docRef = db.collection("players");
        let user_email = user.email;

        docRef.onSnapshot((players) => {
          players.forEach((doc) => {
            data = doc.data();
            if (user_email == data.email) {
              myScore = data.endless_score;
              console.log(myScore); //This log the right score
            }
          });
        });
      });
console.log(myScore); // This logs undefined 

How can I get myScore i.e. the second console log to output the score from firestore?

Upvotes: 0

Views: 342

Answers (2)

Egehan Özsoy
Egehan Özsoy

Reputation: 84

Okay, from what I see you are trying to get the current users when the user logs in but I think attaching a snapshot listener is not the optimal solution. Because first of it would count as a read for every player document there is. What I suggest you to do is this :

  const myUser = (await (await firebase.firestore().collection("players").where("email","==",user.email).limit(1).get()).docs[0].data()

This Will Give You Your Current User's data then you can use it however you want by doing myUser.endless_score. It will also reduce the cost because you are only getting a single document where email is equal to current users email

also don't forget to make your arrow function async in order to use await :)

Upvotes: 1

MikkelT
MikkelT

Reputation: 815

Calling onSnapshot creates a background-call to firestore. It run independently of the rest of your code. So your second console log is practically called immediatly after let myScore, meaning it's still undefined.

As well, onAuthChanged is an observer. It can be triggered at random, depending on when you sign in/out of firestore.

To the functionality you want, sort of, you'd need to rewrite the code to use async/await.

Defining a function() as 'async' and then calling 'await function()' in your code will make the code literally wait for the online call to finish before continuing.

read:

https://javascript.info/async-await

Upvotes: 1

Related Questions