Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
Datos no establecidos después de obtener en useEffect

Intento obtener datos de un servidor usando useEffect hook en react 18.0.0. Después de obtener los datos, quiero establecer el estado con el gancho useStat e. Intenté obtener los datos con la sintaxis .then() y la sintaxis async/await , pero intentar registrar el estado da undefined .

Variante 1) .then() -Sintaxis:

 const fetchData = () => { fetch("http://localhost:8080/user", { method: "GET", credentials: "include", headers: { "Content-Type": "application/json", }, }) .then(response => response.json()) .then(data => { console.log(data); setUser(data); console.log(user); }); }

Variante 2) async/await-Syntax:

 const asyncFetchData = async () => { const response = await fetch("http://localhost:8080/user", { method: "GET", credentials: "include", headers: { "Content-Type": "application/json", }, }); const data = await response.json(); console.log(data); setUser(() => data); console.log(user); }

Gancho de efecto y renderizado:

 useEffect(() => { asyncFetchData(); fetchData(); }, []); return ( <> <span>{'' + user?.username}</span> </> )

Comportamiento esperado:

El objeto de usuario debe registrarse 4 veces en la consola y el nombre de usuario debe mostrarse en la pantalla.

Problemas:

El objeto de usuario se registra dos veces cuando se llama a console.log(data) pero no cuando se llama a console.log(user) . Además, el nombre de usuario no se representa en la pantalla.

Probé varias respuestas en StackOverflow, por ejemplo, esta , pero ninguna funcionó.

¿Cómo resuelvo este error?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!