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

263
Visualizações
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 à 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