Home > OS >  Failing to setState of Functional Component
Failing to setState of Functional Component

Time:05-28

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;
}

CodePudding user response:

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...

CodePudding user response:

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

  • Related