1
    export default function Main({ match }) {
  const userid = match.params.id;
  const [user, setUser] = useState([]);
  async function fetchuser() {
    const response = await api.get('/emps/profile', {
      headers: {
        userid: match.params.id,
      },
    });
    setUser(response.data);
    console.log(response.data);
    console.log(user);
}
 useEffect(() => {
    
    fetchuser();
  }, [match.params.id]);

In the above code the response.data is written into console but user state is empty. Can someone tell me why this is?

SEC
  • 35
  • 6
  • This may be due to the asynchronous nature of `useState`. Your state is not going to be immediately set. – luckongas Jan 15 '21 at 17:10

1 Answers1

0

Two suggestions:

  1. Determine if response contains any data before logging it.
  2. Move your fetchData function into the useEffect hook. https://stackoverflow.com/a/56851963/8943092

Below is an example of how you can test for the existence of data, and here is a live Sandbox.

Note that we use a simple conditional to check if (myData) is truthy. Our useState hook sets no default value, so the conditional returns true once data is present.

In the render method, we use a ternary to check for the existence of data.

Your solution may be slightly different because you set the default value of user to an empty array []. Assuming your API call returns an array, you'll test for data with if (user.length > 0).

import React, { useEffect, useState } from "react";

export default function App() {
  const [myData, setMyData] = useState();

  useEffect(() => {
    function fetchData() {
      setTimeout(function () {
        setMyData("I am user data");
      }, 3000);
    }

    if (myData) {
      console.log(myData);
    } else {
      console.log("No data yet");
    }

    fetchData();
  }, [myData]);
  return (
    <div className="App">{myData ? <p>{myData}</p> : <p>No data yet</p>}</div>
  );
}
It'sNotMe
  • 1,184
  • 1
  • 9
  • 29