• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

210
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error