0

this is my first question in this platform, I hope you can help me out, I have a doubt.

How to put fetch API data (async/await) inside a global scope Array? | Vanilla Javascript

I have this variable called storeItems that is initially empty:

let storeItems = [];

And I created this function called fetchApi to call the data from the API and push it in to the storeItems array, which is declared outside the async function.

async function fetchApi() {
    const dataApi = await fetch('https://fakestoreapi.com/products')
    const dataJason = await dataApi.json()
    dataJason.map((element) => {
        storeItems.push(element)
    })
    showProducts();
}

fetchApi();

It partially works, it only works when i execute the showProducts function inside the fetchApi function.

If I try to access the array properties of storeItems outside the fetchApi I will get undefined. If I console log the array I can see the data in the log, but cannot access to any of the objects inside the array, I get undefined.

Thanks.

  • Well you are populating the array asynchronously. If you're trying to use it immediately, it's still empty. You'll need to wait until it has been filled. – Bergi Oct 19 '22 at 01:27

1 Answers1

0

Perhaps you want to try out top level await?

it requires you to write in the realm of ECMAScript modules. You can do so with using type=module <script type="module">, there is also other numerus of other ways to do so with package.json (for NodeJS) and using options when creating Web or Service Workers.

<script type="module"> 

  const res = await fetch('https://httpbin.org/get')
  const json = await res.json()

  console.log(json)

</script>
Endless
  • 34,080
  • 13
  • 108
  • 131
  • Thanks @Endless for your help, you are right, the answer is here: [link]https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Juan Camilo Escobar Oct 19 '22 at 13:48