0

For context, I am trying to get the user ID and assign it within the database, which is a success. Next, when I call the 'userID' variable after the function (see console log), it doesn't appear to have updated from the first declaration.

      var userID = 'test';
  
  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      userID = user.uid;
      let x = db.collection('users').doc(userID);
      x.get().then(function(doc) {
        if (doc.exists) {
            x.update({Logins: firebase.firestore.FieldValue.increment(1),
            'Last login': firebase.firestore.FieldValue.serverTimestamp()});
            return userID;
        } else {
            // adding Login count
            x.set({Logins: 1, 'Whispers Received': 0});
        }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
      
    } else {
      // No user is signed in.
    }
  });

  console.log(userID);

The 'console.log' prints "test" instead of the user's ID.

user3385829
  • 117
  • 1
  • 9

1 Answers1

1

Welcome to asynchronous world of JavaScript + event loop.

Your console.log(userID) happens before the callback function function(user) inside firebase.auth().onAuthStateChanged can be triggered. So you will always get userId as 'test'. This is expected behaviour.

To explore this in detail, head over to:-

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
  • Oh man, that is so not cool. I tried my best to keep up with the link and the last part helped most. Now it makes sense. I'm thinking I either put my event listeners (these come after the console log) into the 'If' condition. The other option (if this makes sense) is I can put a function around the console log (and event listeners) and call that function, and within the function I ensure that if 'userID' === 'test' then loop and do that function again. – user3385829 Jun 28 '20 at 07:56
  • Nevermind this approach - I used a 'while loop' and it led to a limit on how man times the browser will run the process before shutting it down. – user3385829 Jun 28 '20 at 08:38
  • Figured it out! so I put a function around the entire code and called it within my 'sign in' function. If the user ID exists then I allow the rest of the code to run (except for DOM functions - these I kept outside it). – user3385829 Jun 28 '20 at 09:44