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

261
Vistas
Data not set after fetch in useEffect

I try to fetch data from a server using useEffect hook in react 18.0.0. After the data is fetched, i want to set the state with the useState hook. I tried fetching the data with .then() syntax and the async/await syntax, but trying to log the state gives undefined.

Variant 1) .then() -Syntax:

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);
    });
}

Variant 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);
}

Effect hook and rendering:

useEffect(() => {
    asyncFetchData();
    fetchData();
}, []);

return (
    <>
        <span>{'' + user?.username}</span>
    </>
)

Expected behaviour:

The user object should be logged 4 times in the console and the username should be rendered on screen.

Problems:

The user object is logged two times when calling console.log(data) but not when calling console.log(user). Also, the username is not rendered to the screen.

I've tried several answers on StackOverflow, e.g. this one, but none of them did work.

How do I resolve this error?

about 4 years ago · Juan Pablo Isaza
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