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

258
Vistas
JS fetch: los datos desaparecen o bucle infinito

Esta función aquí me ha estado causando algunos problemas por un tiempo.

Al imprimir "res", muestra bien el objeto y sus campos, sin embargo, cuando está fuera de este bucle, los datos no están definidos, lo cual es comprensible teniendo en cuenta que la variable solo se inicializa dentro de la función.

Sin embargo, si trato de usar setData (campo) o setServerUser (campo) dentro, se ejecuta recursivamente.

Pensé que la solución a esto sería llamar a setData(field) o setServerUser(field) fuera del ciclo, aunque el mismo resultado.

código:

 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 Respuestas
Responde la pregunta

0

Algo que ver con useEffect, useState y se sobrescriba entre sí

 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 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