I’m trying to use the omdbapi and I used async function to fetch the data. I convert the const data to an array using the Object.key() so that I can use the map() to send the data to innerHTML but it always says undefined. I wanted to convert the data into a new array using a map() and show it in the html using movieHTML(). Please help
const movieListEl = document.querySelector('.shows');
async function main (event) {
const url = `https://www.omdbapi.com/?apikey=39a36280&s=${encodeURI(event)}`;
const search = await fetch(`${url}`);
const data = await search.json();
// console.log(data.Search)
// if (data.Response === 'True') {
// console.log(data.Search)
// }
let dataKeys = Object.keys(data.Search);
movieListEl.innerHTML = dataKeys.map((movie) =>
console.log(movieHTML(movie))).join("");
}
main('squid game');
function movieHTML (details) {
return `<div class="shows__content">
<figure class="shows__poster">
<img src="${details.Poster}" alt="" class="poster">
</figure>
<div class="poster__description">
<h4 class="poster__title">${details.Title}</h4>
<p class="poster__year">${details.Year}</p>
</div>
</div>
`
}
<div class="shows">
</div>
>Solution :
Why are you using Object.keys?:
let dataKeys = Object.keys(data.Search);
movieListEl.innerHTML = dataKeys.map((movie) =>
console.log(movieHTML(movie))).join("");
}
If you examine your data, you’ll see that data.Search is an array. So its "keys" are the index values (0, 1, 2, etc.). Sending those integer values to movieHTML() doesn’t seem productive.
Instead of looping over the indexes of the array, loop over the array itself and send each object therein to the function:
movieListEl.innerHTML = data.Search.map((movie) =>
console.log(movieHTML(movie))).join("");
}