Skip to content
Advertisement

Fetch data changing on reload from array to undefined

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

Return of first console.log First log

After reload Log after refreshing page (no code changed)

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()

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement