• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

211
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 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda