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.