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();
});
CodePudding user response:
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 >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.