unable to use data from fetch function

Viewed 23

i am unable to use data fetched from an api into a global variable. i declared a variable globally and tried to copy the contents from the fetch api into the said global variable but i dont see any results in it. as also written in the code i try to console log the value of mainData outside of the scope of the function but it is logging an empty array. i did not declare main data into the scope of any function so it should not behave this way. so i wish to ask why is mainData not available to me when i clearly made it a global variable. thanks

const url = "https://dummyjson.com/products";

var mainData = [];


const fetchData = async() => {
  const resp = await fetch(url);
  const data = await resp.json();
  return data;
     
}


const display = async() => {
   const getData = await fetchData();
   mainData = [...getData.products];
   //console.log(mainData);
}

display();

console.log(mainData);



0 Answers
Related