0

I want to use a variable value based on conditional statement of onAuthStateChange of Firebase Authentication but it seems the variable value is not assigned.

let isLoggedIn

onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    console.log(true)
    isLoggedIn = true
  } else {
    // User is signed out
    console.log(false)
    isLoggedIn = false
  }
});

console.log(isLoggedIn)

but the console result is:

undefined
true //I already logged in

how do I assign value of a variable outside onAuthStateChanged?

Avocado
  • 29
  • 6
  • The problem is not so much **where** you access the variable, but **when** you access it. If you check the order of the log output, you'll see that the `console.log(isLoggedIn)` runs before the other have run, because `onAuthStateChanged` is an asynchronous handler. There is no "fix" for this, because it's not a bug - but normal behavior for asynchronous calls. All code that needs to respond to the auth state needs to be inside the callback, be called from there, or otherwise synchronized. – Frank van Puffelen Oct 31 '22 at 00:32

0 Answers0