1

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?

Philip F.
  • 1,167
  • 1
  • 18
  • 33

0 Answers0