Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
Failing to setState of Functional Component

Assuming the ProfileService API returns an appropriate object, why is the data state variable undefined when I attempt to log it?

NOTE: I am only having this issue in functional components; the same code works in a Class component.

export default function Id() {
  const [data, setData] = useState({});

  useEffect(() => {
    console.log("Mounted.");
    fetchProfile("123");
  }, []);

  const fetchProfile = (id) => {
    ProfileService.getProfile(id).then((response) => {
      if (response.status === 200) {
        setData(response.data);
        console.log("200 OK", data);  // returns "200 OK undefined"
      }
      console.log("Called ", data); // returns "Called undefined"
    });
  };

  return null;
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The setter that is returned from a useState is asynchronous. You won't see the change until the next time your component function is invoked (the change of state will cause that to happen near-immediately)

Of course, you know what the value you just set is...

about 4 years ago · Juan Pablo Isaza Report

0

When you tried to get a new state value at once after setting a state, you always will have a previous value.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!