I’m getting some weird error. Just starting with typescript. When i write console.log(data) for the first time i get an array with objects inside. The problem occurs when i reload the webpage without touching anything. My console log returns undefined.
const Home = (): JSX.Element => {
  const [data, setData] = useState<any>();
  const [loading, setLoading] = useState<boolean>(true);
  const fetchApi = () => {
    fetch("https://fakestoreapi.com/products")
      .then((res) => {
        return res.json();
      })
      .then((data) => setData(data));
      console.log(data)
  };
  useEffect(() => {
    fetchApi();
    setLoading(false);
  }, []);
  return(
      <div>
      </div>
  )
};
Advertisement
Answer
you need to console.log inside “then”
.then((data) => {
   setData(data));
   console.log(data)
})
if you console.log the data state under setData it will show undefined, you can console.log(data) state inside useEffect after fetchApi()

