Home > front end >  How to loop through data from an API call and render each to a div?
How to loop through data from an API call and render each to a div?

Time:10-25

I'm trying to figure out how to loop through my API data and render data to each div. Specifically, to have info from each movie in its own div.

HTML:

  <div id="main">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    </div>

My javascript so far is just being able to loop through it on the console:

const loopData = () => {

    let apiCall = `https://ghibliapi.herokuapp.com/films`;

    fetch(apiCall)
        .then(response => response.json())
        .then(data => {
            for(let i = 0; i < data.length; i  ) {
                let obj = data[i];
            
                console.log(obj.title);
            }
            
;})
};

loopData()

Here is what my data looks like:

Data from console

CodePudding user response:

You can create div elements when you receive the data from API and add into them textNode to the movie's title and then append them as children to the div whose has .main id.

const loopData = () => {

  let apiCall = `https://ghibliapi.herokuapp.com/films`;
  const mainEle = document.getElementById('main');

  fetch(apiCall)
    .then(response => response.json())
    .then(data => {
      for (let i = 0; i < data.length; i  ) {
        let obj = data[i];

        const div = document.createElement('div');
        let textNode = document.createTextNode(obj.title);
        div.appendChild(textNode)
        main.appendChild(div);
      }

      ;
    })
};

loopData()
<div id="main"></div>

Also, you can use reduce method.

const loopData = () => {

  let apiCall = `https://ghibliapi.herokuapp.com/films`;
  const mainEle = document.getElementById('main');

  fetch(apiCall)
    .then(response => response.json())
    .then(data => {
      const html = data.reduce((acc, movie) => {
        acc  = `<div>${movie.title}</div>`
        return acc;
      }, '')
      main.innerHTML = html
    })
};

loopData()
<div id="main"></div>

CodePudding user response:

  • All you need is a helper function that handles the creation of your desired element with the data you provided.
  • I have created the function createMyCustomeElement(data, id), this takes two arguments one for the data and the second one is the id of the element in which we will append created legal HTML.
  • Just for more readable way I have changed for-loop to forEach loop.

const loopData = () => {

  let apiCall = `https://ghibliapi.herokuapp.com/films`;

  fetch(apiCall)
    .then(response => response.json())
    .then(data => {
      data.forEach(val => {
        // calling createMyCustomeElement that takes data and id of element in which data gonna append
        createMyCustomeElement(val, "#main");
      })
    })
};

loopData()
// this function will handle in which element you want to insert and how you want to create element as per your need.
function createMyCustomeElement(data, id) {
  const parent = document.querySelector(id);
  let createdTitle = `<div >
  <h5>${data.title}</h5>
  <img src="${data.image}"/>
  <p>${data.description}</p>
  </div>`;
  parent.innerHTML  = createdTitle;
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Jost";
}

#main {
  margin: 20px;
}

.card {
  padding: 20px;
  box-shadow: 0 0 15px 0 #b4b4b465;
  margin-bottom: 10px;
}

.card img {
  object-fit: cover;
  width: 100%;
  height: 200px;
}
<div id="main">
</div>

  • Related