Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

238
Vistas
Firebase onAuthStateChanged always returning undefined

I've been trying to make a util method which will return either the user object or if the user object exists. With no params it should return a boolean and with the param "getUser" it should return the user object, but it is always returning undefined. This seemed to work for a while, but then I took a break and came back and it was always returning undefined. Code below

import { getAuth, onAuthStateChanged } from "firebase/auth";
export default function checkAuthState(type?:string){
    const auth = getAuth()
    onAuthStateChanged(auth, (user) => {
        if (user) {
            if(!type) return true
            if(type === "getUser") return user
            else return true
        } else {
            if(!type) return false
            else return false
        }
      });
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your return true returns a value to onAuthStateChanged, which is what calls your callback. The onAuthStateChanged is not doing anything with that value.

If you want to have a promise that resolves once the initial user state has been restored, you can do that with:

function checkAuthState(type?:string){
  const auth = getAuth()
  return new Promise((resolve, reject) => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      if (user) {
        if(!type) resolve(true)
        if(type === "getUser") resolve(user)
        else resolve(true)
      } else {
        if(!type) resolve(false) false
        else resolve(false)
      }
      unsubscribe();
    });
  })
}

And then call it like this:

checkAuthState().then((result) => {
  console.log(result);
})

Or when using async/await:

const result = await checkAuthState();
console.log(result);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda