0

I have the following js file for a webpage to query firebase. The page is protected from users who are not logged in. I tried to access some user properties but when I query my variable on the browser, userEmail is still undefined.

const auth = firebase.auth();
const db = firebase.firestore();

function checkIfLoggedIn() {
    auth.onAuthStateChanged(user => {
        if(!user) {
            window.href = 'login.ejs';
        } else {
            var username = user.email;
            console.log(`${username} has logged in!`);
            return username
        } 
    });
};

var userEmail = checkIfLoggedIn();
console.log(userEmail); // output is undefined
Cadell Teng
  • 224
  • 3
  • 23
  • `window.href = 'login.ejs';` is not valid JS. It would be `window.location.href = 'login.ejs';` – mplungjan Apr 22 '20 at 06:33
  • 1
    And you cannot return a value from a function that uses an ASYNC method to get the value – mplungjan Apr 22 '20 at 06:34
  • just add `return` before `auth.onAuthStateChanged` so it becomes `return auth.onAuthStateChanged(user => ...)` and because it's async you need to wait for the promise not `checkIfLoggedIn().then(username => console.log(username))` – rksh1997 Apr 22 '20 at 06:34

0 Answers0