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

254
Visualizações
JS fetch - data disappear or infinite loop

This function here has been causing me some trouble for a while.

When printing "res" it shows the object and its fields fine, however when outside of this loop data is then undefined, which is understandable considering the variable is only being initialized within the function.

However if I try to use the setData(field) or setServerUser(field) inside it executes recursively.

I thought the solution to this would be to call either setData(field) or setServerUser(field) outside the loop, though same result.

code:

    const [ serverUser, setServerUser ]=useState('')
    const [ data, setData ]=useState('')

    async function fetchProfile(){
        const res = await fetch(
            "http://XXX.XXX.XXX.XXX:8080/User/getByEmail", {
            method: "POST",  
            headers:{"Content-Type":"application/json"},
            body:JSON.stringify( { email : user.email }  ) } )

        const data = res.json().then((res) => {


            // V both of these causes infinite looping
            // V i dont think this is the right spot to set - but res doesnt exist outside
            //setServerUser(res)
            //setData(res)

            console.log(res) // < this actually prints the object perfectly
        });
        console.log(res) // < equal to undefined here

        // V both of these causes infinite looping
        // V this makes the most sense to me setting here but yet same result
        //setServerUser(data);
        //setData(data)

        console.log("data" + data) // < this returns data[object Promise]
    }

    fetchProfile();
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Something to do with useEffect, useState and it overwriting eachother

 const [ serverUser, setServerUser ]=useState('')

//3. passing an empty array for on mount (when the page loads)
useEffect(() => {
    fetch("http://XXX.XXX.XXX:8080/User/getByEmail", {
        method: "POST",  
        headers:{"Content-Type":"application/json"},
        body:JSON.stringify( { email : user.email } )
    })
    .then(response => response.json())
    .then(json => { setServerUser(json) })
},[]) 
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