0

I have a problem. docRef.get().then(...) is a function which works asynchronously. Since it returns immediately, username will not be set. How could I get the value and set it to the variable username?

var username;
var kontostand;
var ticket;



firebase.auth().onAuthStateChanged(function (user) {
  if (user) {
    // User is signed in.
    document.getElementById("user_div").style.display = "block";
    document.getElementById("login_div").style.display = "none";

    var docRef = db.collection("users").doc(user.uid);

    // Get the data from the user
    docRef.get().then(function (doc) {
      if (doc.exists) {
        //console.log("Document data:", doc.data());
        kontostand = doc.data().kontostand;
        ticket = doc.data().ticket;
        username = doc.data().username;
      } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
      }
    }).catch(function (error) {
      console.log("Error getting document:", error);
    });

    var user = firebase.auth().currentUser;

    if (user != null) {

      document.getElementById("user_para").innerHTML = "Welcome User : " + username;

    }
  • You can't assign variables asynchronously like that. – evolutionxbox May 22 '20 at 11:06
  • @evolutionxbox thanks for the comment. No it didn't. –  May 22 '20 at 11:11
  • Everything you want to happen after the `docRef.get()` needs to be inside the `function (doc)` callback. Or you use `async`/`await`. –  May 22 '20 at 11:11
  • @ChrisG thank you for your comment! And how the `function (doc)` looks like? –  May 22 '20 at 11:12
  • It should do, as that's what you're trying to do. – evolutionxbox May 22 '20 at 11:16
  • @evolutionxbox I didn't understood it. I'm a beginner... –  May 22 '20 at 11:24
  • 1
    Maybe consider explaining what you don't understand, or even what you're hoping to achieve? (Rather than saying "no it didn't") – evolutionxbox May 22 '20 at 11:28
  • @evolutionxbox thanks! I' don't get how to implemante the callback function –  May 22 '20 at 12:36
  • You already have the callback function. The first line inside is `if (doc.exists)`. A bit further down you're setting `username`, then the function basically ends. This is where you need to insert the rest of the code, the code that needs `username`. –  May 22 '20 at 12:51
  • @ChrisG thank you! I'm confused. i'm sorry.. :( –  May 22 '20 at 12:51

0 Answers0