0

I am trying to insert API data into html using JavaScript. I have declared an empty itemsArray, executed a function which fetch data from API and push that data to itemsArray.

Now I want to map over itemsArray, return div element with data and insert it into HTML using innerHTML, but my itemsArray is empty. Anyone knows why is that happen?

Here is my code:

let itemsArray = [];

const fetchData = () => {
  fetch('http://localhost:3000/items')
    .then(response => {
      if (!response.ok) {
        throw Error(response.status)
      }
      return response.json();
    })
    .then(data => {
      data.items.map(item => {
        itemsArray.push(item);
      })
    })
    .catch(error => console.log(error))
}

fetchItems();

const itemsList = document.querySelector('#items-list');

let item = itemsArray.map(item => {
  return `
    <div class="price">
      ${item.price}
    </div>
  `;
}).join('');

itemsList.innerHTML = item;
adn98
  • 193
  • 2
  • 4
  • 12
  • Your populating `itemsArray` in `fetchData` function. However, you're never calling this function. you're calling `fetchBooks` instead. This might be the reason. – dfvc Jan 30 '21 at 21:42
  • Sorry, I made mistake while copying code. Now it's okay. But function's name is not a reason – adn98 Jan 30 '21 at 21:45
  • Ok, then it should be a sync problem, Basically when you're running the code for generating the divs, the fetch it's not finished/resolved yet. You should try to await for the function to end: `await fetchData()`. You can also consider `fetch(...).then(...).catch(...).finally('generate divs here')`. – dfvc Jan 30 '21 at 22:00

0 Answers0