0

I'm making a Watchlist app. I got movies via API, rendered them on the page, using fetch/.then methods inside a for loop.

Then after the for loop I try to grab all the buttons "remove" on each movie and add event listener to them, but it doesn't work. Could you please help to correct my bug?

for (let i = 0; i < movies.length; i++) {
  fetch(`https://www.omdbapi.com/?i=${movies[i]}&apikey=123`)
    .then(res => res.json())
    .then(movie => {
        containerList.innerHTML += `<div class="movie"></div>})
    
    //here outside of the loop I write the code that doesn't work
    
    document.querySelectorAll(".buttonClass").forEach(button => {
        button.addEventListener("click", () => {
          localStorage.clear()
          containerList.innerHTML = ""
        })
      })

The last part of code doesn't work, maybe because it's asynchronous and I haven't indicated it in the code. Should I use .finally in this case?

Here's the full page code (only this particular page, there is also the 2d one with the search field): https://codepen.io/btb8293/pen/KKoLOmZ

Thank you in advance!

isherwood
  • 58,414
  • 16
  • 114
  • 157
Smith82
  • 19
  • 5
  • 1
    You're missing a closing backtick, which you can see in the code highlighting. I'm not sure if that's causing your subsequent code to fail. – isherwood Aug 26 '22 at 19:43

1 Answers1

0

I am not sure why you want every button to clear localStorage en empty the container, but here is a delegation script https://codepen.io/mplungjan/pen/KKoLOvQ

localStorage has nothing to do with the DOM. You need to have code that adds and removes from the watchlist and each time rewrites localStorage. I see only code the reads the localStorage.

You need to change <div class="movie"> to <div class="movie" data-key="${movies[i]}">

and then you can use parent.dataset.key and do

<!-- language: lang-js -->
const containerList = document.getElementById("containerList");
const noInfoList = document.getElementById("noInfoList");
let watchList = JSON.parse(localStorage.getItem("watchList"));
if (watchList.length===0) watchList= ["tt0089880", "tt0489270"]; // debug - remove after test
console.log(watchList);
containerList.innerHTML = "";
noInfoList.style.display = "none";
watchList.forEach(key => {
  fetch(`https://www.omdbapi.com/?i=${key}&apikey=...`)
    .then((res) => res.json())
    .then((movie) => {
      console.log(movie);
      containerList.innerHTML += `<div class="movie" data-key="${key}">
  <div class="movieImg">
    <img id="poster"src="${movie.Poster}">
  </div>
  <div class="movieInfo">
    <div class="movieNameRate">
      <h3 class="movieName">${movie.Title}</h3>
      <p class="movieRate"><img src="Icon star.png">${movie.imdbRating}</p>
    </div>
    <div class="movieDetails">
      <p class="movieTime">${movie.Runtime}</p>
      <p class="movieGenre">${movie.Genre}</p>
      <button class="remove" id="btt"><img src="Icon -.png"> Remove</button>
    </div>
    <p class="movieDescription">
      ${movie.Plot}</p>
  </div>
</div>`;
    })
});

/*const saveMovie = key => {
  if (!watchList.includes(key)) watchList.push(key);
  localStorage.setItem("watchList", JSON.stringify(watchList));
};*/
const deleteMovie = key => {
  watchList = watchList.filter(item => item !== key);
  localStorage.setItem("watchList", JSON.stringify(watchList));
   console.log("after delete",watchList)
};

containerList.addEventListener("click", (e) => {
  const tgt = e.target.closest(".remove");
  if (tgt) {
    const parent = tgt.closest(".movie");
    console.log("deleting",parent.dataset.key)
    deleteMovie(parent.dataset.key);
    parent.remove();
  }
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    @Smith82, please don't ask new questions in comments. – isherwood Aug 26 '22 at 19:41
  • if I just add ```tgt.closest(".movie").remove()``` it doesn't work... – Smith82 Aug 26 '22 at 20:00
  • See update....... – mplungjan Aug 26 '22 at 20:02
  • Thank you so very much. I am new to coding and you really help me a lot. Now I see that the movie is deleted, but it's still in local storage and when I refresh the page it appears again. I try to delete it via the following code: localStorage.removeItem(tgt.closest(".movie")), but it doesn't work. What should be changed? Thank you in advance. – Smith82 Aug 26 '22 at 20:33
  • Thanks in advance! Local storage array: ["tt0089880", "tt0489270"] 0: "tt0089880" 1: "tt0489270" – Smith82 Aug 27 '22 at 06:07
  • I added a data attribute so you can do parent.dataset.key. Please see the update to the other functions too since I thought you used the name of the movie and now see the IMDB key – mplungjan Aug 27 '22 at 07:27
  • Thank you very much. I made changes, but it still doesn't work for some reason...I would be so much grateful to you if you could make changes in codepen. – Smith82 Aug 27 '22 at 08:14
  • See update and updated pen – mplungjan Aug 27 '22 at 11:26
  • 1
    It works! You helped me so very much, thank you! – Smith82 Aug 27 '22 at 12:01
  • You are welcome. Please have a [look here too](https://i.stack.imgur.com/LkiIZ.png) – mplungjan Aug 27 '22 at 12:14