Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

240
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda