Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

appending data from Api to the Dom

I am fetching data from an API (TMDB) and creating an array to loop through the data, I get everything that I want in the console in the browser but I only get the last index of the array when I try to append it to the DOM. Thank you

const serachbtn = document.querySelector('.search');
const input = document.querySelector('input');

const p = document.createElement('p');
document.body.appendChild(p);


let movieArray = [];


async function getmovie(){

    const inputValue = input.value;

    const apiUrl = `https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&query=${inputValue}`;

    try{

        const response = await fetch(apiUrl);
        const movie = await response.json();

        //const picture = "https://image.tmdb.org/t/p/w500/" + movie.results[0].poster_path;
        
        let movieArray = movie.results;

        movieArray.forEach(searchie => {
            
            console.log("title: "+searchie.original_title);
            console.log("Overview: "+searchie.overview);
            
            p.innerHTML = searchie.original_title;

        });
        
    }catch(error){

        console.log('something went wrong');
    }
}

serachbtn.addEventListener('click', (e)=>{

    e.preventDefault();
    getmovie();

    });

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The loop replaces your <p> tag’s innerHTML with each iteration, leaving only the last one visible when the loop ends. Instead of replacing, you can append to the html with +=.

Run the snippet and press the "Search" button to see…

const serachbtn = document.querySelector('.search');
const p = document.createElement('p');
document.body.appendChild(p);

async function pretendFetch() {
  const movies = [
    { original_title: 'The Godfather' },
    { original_title: 'Star Wars' },
    { original_title: 'Jaws' },
  ];
  return Promise.resolve(movies);
}

async function getmovie() {
  try {
    const movieArray = await pretendFetch();
    movieArray.forEach(searchie => {
      console.log("title: " + searchie.original_title);

      // this is the important change: append, don't replace
      p.innerHTML += searchie.original_title + '<br/>';
    });
  } catch (error) {
    console.log(error);
  }
}

serachbtn.addEventListener('click', (e) => {
  e.preventDefault();
  getmovie();
});
<button class="search">Search</button>

There are numerous other ways to add to the DOM, including by adding a new tag for each API result.

To do that, you’d use appendChild() within the loop, instead of just at the start.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading