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

214
Visualizações
UseEffect to fetch user number and pass to CurrentUser state on unsubscribe (order of execution)

I'm using Firebase to authenticate a user, then using the Firebase ID (uid) to setUserData with the user's row in Postgres via a HTTP request. It works as written, but I'm having trouble with the order execution of these functions because the console is returning 'invalid input syntax for type integer: "undefined"'.

The desired order is

  1. Wait for the authentication to return a uid
  2. Execute the HTTP request using uid
  3. Redirect to "/"

Instead, it seems to run 2, 1, 3, 2. On the second HTTP attempt data is populated. This explains why I sometimes need to log out and log back in for certain components to load with the user's data.

What am I missing to ensure correct order of operations?

Login.js

   async function handleSubmit(e) {
        e.preventDefault()
    
        try {
          setError("")
          setLoading(true)
          await login(emailRef.current.value, passwordRef.current.value)
          setLoading(false) 
          history.push("/")   
        } catch {
          setLoading(false)  
          setError("Failed to log in")
        }

Auth.js

   useEffect(() => {

        const fetchProfile = (uid) => {
            axios.get(`/user/${uid}`)
            .then(async (response) => {
                setUserData(await response.data)
                console.log(response.data)
                console.log(uid)
            })
            .catch(error => console.error(`Error: ${error}`))
        }

        const unsubscribe = auth.onAuthStateChanged(async user => {
            user && fetchProfile(user.uid)
            setCurrentUser(user)
            setLoading(false)
        })

        return unsubscribe

    }, [])

    const value = {
        currentUser,
        userData,
        login,
        signup,
        logout,
        resetPassword,
        updateEmail,
        updatePassword
    }

    return (
        <AuthContext.Provider value={value}>
            { !loading && children}
        </AuthContext.Provider>
    )
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I would remove fetchProfile as a function and move unsubscribe outside of useEffect and have currentUser as a dependency to useEffect. useEffect would only run when currentUser has changed.

...
const unsubscribe = auth.onAuthStateChanged(async user => {
        //only if there is a user setCurrentUser
       if(user){
         setCurrentUser(user)
         setLoading(false)
       }
   })

useEffect(() => {
        if(!currentUser) return
        axios.get(`/user/${currentUser.uid}`)
          .then(async (response) => {
              setUserData(await response.data)
              console.log(response.data)
              console.log(uid)
          })
          .catch(error => console.error(`Error: ${error}`))
    }, [currentUser])
...
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