Would like to be able to click the images and display data from a second fetch call using the imdbID that matches the clicked poster.
I'm trying to print movie posters to the page - the movie posters will then be clickable - on click they will display Director, actors and year info in a div ("info").
I can't figure out how to make all of the images react to the click event. (I think it's because img id, but I can't get the code to work if I get the images by class). I can get the data from the second fetch but it only works on the first poster and with data from the last image. (The first poster is also the only one that is clickable.
CodeSandbox here: https://codesandbox.io/s/1ojvormxn7
I can console log the data from the second call but it doesn't match the image and I'm not sure how I can print it where it needs to go.
document.getElementById("searchButton").addEventListener("click", () => {
const inputSearch = document.getElementById("searchInput").value;
//console.log(inputSearch);
fetch(`https://www.omdbapi.com/?apikey=d2d93339&s=${inputSearch}`)
.then(response => response.json())
.then(data => {
console.log(data);
let posterImage = "";
let imdb = "";
data.Search.map(results => {
//console.log(results.Poster);
return (
(posterImage += `<img id="resultPic" class="resultPic" src="${
results.Poster
}">`) && (imdb = results.imdbID)
);
});
document.getElementById("app").innerHTML = posterImage;
document
.getElementById("resultPic")
.addEventListener("click", getInfo => {
fetch(`https://www.omdbapi.com/?apikey=d2d93339&i=${imdb}`)
.then(response => response.json())
.then(data => {
console.log(data);
});
});
});
});
What you need to do is to use a uniq id for each img
tag, to do so, you can use imdbID
like this :
<img id=resultPic-${results.imdbID}
This way you always have a uniq id, then after render the img tags, you can map the data again and this time add click event to each img tag, and you don't need really to have another call to the api, you can do it like this :
data.Search.map(results => {
document
.getElementById(`resultPic-${results.imdbID}`)
.addEventListener("click", getInfo => {
console.log(results);
});
});
I update your code here, as you can see on console logs, once you click on each poster, you will rceive data for that poster which you can use it anywhere you want :