Search code examples
javascriptlocal-storagestorage

Trying to make a movie likeable one time


I'm trying to make movies likeable one time by storing them in an array like this:

let likedMovies = [];
const movieLike = document.getElementById("likeButton");
likedMovies = JSON.parse(localStorage.getItem("likedMovies"));
movieLike.addEventListener("click", () => {
  if (likedMovies.indexOf(allMovies[i].name) === -1) {
    confirm("Movie liked");
    axios.patch(`url`);
    likedMovies.push(allMovies[i].name);
    localStorage.setItem("likedMovies", JSON.stringify(likedMovies));
    return true;
  }
  confirm("Movie already liked");
  return false;
});

it was working this afternoon but now the console display an error log saying this: "script.js:75 Uncaught TypeError: Cannot read properties of null (reading 'indexOf') at HTMLDivElement." and when I log my likedMovies array, it says that arrays's "null", could you please help me understanding why it doesn't work ?


Solution

  • The problem is that you are reassigning likedMovies with the result of JSON.parse which is null if it's unable to parse it.

    let likedMovies = JSON.parse(localStorage.getItem("likedMovies")) || [];
    

    This should solve the error, but also you can do some optimization by storing it as an Object.

    let likedMovies = JSON.parse(localStorage.getItem("likedMovies")) || {};
    const movieLike = document.getElementById("likeButton");
    movieLike.addEventListener("click", () => {
      if (likedMovies[allMovies[i].name]) {
        confirm("Movie liked");
        axios.patch(`url`);
        likedMovies[allMovies[i].name] = true;
        localStorage.setItem("likedMovies", JSON.stringify(likedMovies));
        return true;
      }
      confirm("Movie already liked");
      return false;
    });
    

    Now your search will happen not in linear time which is O(n) but in constant O(1). Tiny performance improvement.