Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading