How to output multiply divs with data from API

Viewed 111

I'm using an API and I'm absolutely clueless how to output 3 divs with data from 3 different objects. What's happening is that JS outputting only one div. I wonder how can I prevent JS from overriding?

  function reviews(id){
    fetch(`https://api.themoviedb.org/3/movie/${id}/reviews?api_key=9250b9e19854d9deaa571f4074bc38a3&language=en-US&page=1` ,{
        method: "GET",
    })
    .then(response => {
        return response.json();
    })
    .then(data => {
        console.log(data);
        output = '';
        for (i = 0; i <3; i++) {
            output = `
            <img src="https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png" class="align-self-start mr-3">
            <div class="media-body>
            <h5 class="mt-0 review-title">A Review by ${data.results[i].author}</h5>
            <p class="review-author">${data.results[i].author}</p>
            <p class="review-paragraph">${data.results[i].content.substring(0,200)}... <a href="#" class="see-more">see more</a></p>
            </div>
            `  
        }
        document.querySelector('.reviews-container').innerHTML = output;
    })
    .catch(showAlert())
  }
1 Answers

You are outputting html string in the DOM after the loop has executed. That will only output the last html string in the DOM.

You need to append the html, not overwrite it and add the html to DOM inside the loop

Use Element.insertAdjacentHTML() function

for (i = 0; i < 3; i++) {
    ...
    document.querySelector('.reviews-container').insertAdjacentHTML("beforeend", output); 
}

You could also use += operator

for (i = 0; i < 3; i++) {
  ...
  document.querySelector('.reviews-container').innerHTML += output;
}

For performance reasons, you should move following statement

document.querySelector('.reviews-container')

out of the loop body and save it in some variable.

const el = document.querySelector('.reviews-container');

for (i = 0; i <3; i++) {
     ...
     el.insertAdjacentHTML("beforeend", output); 
}

You could also concatenate the HTML string with output variable and then set the innerHTML of the element after the loop has executed.

This is better than accessing DOM in the loop.

 for (i = 0; i <3; i++) {
      output += `...`  
 }
  
 document.querySelector('.reviews-container').innerHTML = output;
Related