0

I have a problem. I get the information of a user via firestore and I want to create a dynamic textfield with the username. So I'm saving the name of the user in a variable. But when I call the username variable later, it is undefined. What is the problem? With console.log in docRef.get().then(function (doc) { ... } the correct value is there, but the problem is at document.getElementById("user_para").innerHTML = "Welcome User : " + user.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;

    }

  } else {
    // No user is signed in.
    document.getElementById("user_div").style.display = "none";
    document.getElementById("login_div").style.display = "block";


  }
});

1 Answers1

0

This is because docRef.get().then(...) is a function which works asynchronously. This means that it returns immediately, even before a result is present, and executes its code only when the result (or failure to obtain one) is there.

Since it returns immediately, username will not be set, because that variable will be populated later, when the result is present.

// 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;

    // not really needed here: var user = firebase.auth().currentUser;
    // user will be non-null, so no check required
    document.getElementById("user_para").innerHTML = "Welcome User : " + username;

  } else {
    // doc.data() will be undefined in this case
    console.log("No such document!");
  }
}).catch(function (error) {
  console.log("Error getting document:", error);
});
Daniel F
  • 13,684
  • 11
  • 87
  • 116
  • Thanks for the answer. And how could I fill the variable `username ` correctly? –  May 22 '20 at 06:49
  • Thank you verz much! Is there a option to save the username in variable? –  May 22 '20 at 07:39