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

123
Visualizações
variable undefined in useEffect

I am trying to use the value of currentUser in the function inside of the useEffect Hook, but the value seems not to be the user's object, that I want it to be when using it. Here is the code:

function Chat() {   

    const currentUser = useAuth()

    useEffect(() => {
        const fetchParticipants = async () => {
            console.log(currentUser.uid) // not defined
        }
        fetchParticipants()
    }, [])
}

That is the useAuth() function that is being called

export function useAuth() {
    const [ currentUser, setCurrentUser ] = useState();

    useEffect(() => {
        const unsub = onAuthStateChanged(auth, user => setCurrentUser(user));
        return unsub;
    }, [])

    return currentUser;
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The initial value of currentUser is going to be undefined because that is what you (don't) pass to the state when you set it up in your hook.

So the effect is first going to run with undefined as the value of currentUser.

Later, the onAuthStateChanged will trigger and update the state.

This will trigger a re-render and currentUser will be the value you want.

However, your effect will not re-run because the dependency array is []. You need to tell it to re-run the function when the value updates.

useEffect(() => {
    const fetchParticipants = async () => {
        console.log(currentUser.uid) // not defined
    }
    fetchParticipants()
}, [currentUser]) // <-------------------- Dependancy array
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