Home > Software design >  How to filter a loop through local storage
How to filter a loop through local storage

Time:01-28

I'm trying to add links to my navbar for searches that users have made, as well as if the user favorites the link. What I'm currently trying to achieve is that if, if the "past searched" section already contains the current search, don't add the current search to avoid duplicates. I am using localStorage to store this data with a stringified array (alreadySearched) and check if this array includes the current search; my problem is that the function always returns false. The same thing happens for the favorites dropdown. What am I doing wrong?

Here's my code:

// primary movie information (API #1)
var getMovie = function(title) {
  $("#result").addClass("hidden")
  $("#main").removeClass("hidden");
  $("#search-form").trigger("reset");
  //format the OMDB api url 
  var apiUrl = `http://www.omdbapi.com/?t=${title}&plot=full&apikey=836f8b0`
  //make a request to the url 
  fetch(apiUrl)
    .then(function(response) {
      // request was successful 
      if (response.ok) {
        response.json().then(function(movieData) {
          // console.log(movieData)
          var movieTitle = movieData.Title
          getMovieId(movieTitle);
          getSoundTrack(movieTitle);
          getTrailer(movieTitle);
          var movieObj = {
            title: movieTitle,
          }
          var pastSearches = loadPastSearches();
          var alreadySearched = false
          if (pastSearches) {
            pastSearches.forEach(s => {
              if (s.title === movieTitle) {
                alreadySearched = true;
              }
            })
          }
          if (!alreadySearched) {
            for (var item of pastSearches) {
              let searchEl = document.createElement("a")
              let pastSearchTitle = item.title
              $(searchEl).text(pastSearchTitle)
              $(searchEl).addClass("past-search-item");
              $("#past-search-dropdown").append(searchEl)
              $(searchEl).click(function(e) {
                e.preventDefault();
                let title = pastSearchTitle
                getMovie(title)
                getQuotes(title)
              });
            }
          }
          saveSearch(movieObj)
          showMovie(movieData);
        });
      } else {
        alert("Error: title not found!");
      }
    })
    .catch(function(error) {
      alert("Unable to connect to CineXScore app");
      console.log(error)
    });
};


// save past search
var saveSearch = function(movieObj) {
  var pastSearches = loadPastSearches();
  pastSearches.push(movieObj);
  localStorage.setItem("movieObjects", JSON.stringify(pastSearches))
}
loadPastSearches = function() {
  var pastSearches = JSON.parse(localStorage.getItem("movieObjects"));
  if (!pastSearches || !Array.isArray(pastSearches)) {
    var pastSearches = []
  }
  return pastSearches;
}
// dropdown favorite soundtrack buttons 
var saveTrack = function(trackObj) {
  var faveTracks = JSON.parse(localStorage.getItem("trackObjects"));
  if (!faveTracks || !Array.isArray(faveTracks)) {
    var faveTracks = []
  }
  var alreadySearched = false
  if (faveTracks) {
    faveTracks.forEach(t => {
      if (t.name === trackObj.name) {
        alreadySearched = true;
      }
    })
  }
  if (!alreadySearched) {
    let trackEl = document.createElement("a")
    $(trackEl).addClass("fave-track");
    $(trackEl).text(trackObj.name);
    $(trackEl).attr("href", trackObj.url);
    $(trackEl).attr("target", "_blank")
    $("#favorite-tracks-dropdown").append(trackEl)
  }
  faveTracks.push(trackObj);
  localStorage.setItem("trackObjects", JSON.stringify(faveTracks))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Navigation Menu -->
<nav >
  <a id="logo" >CineXScore</a>
  <div >Past Searches
    <i ></i>
    <div id="past-search-dropdown" >
      <a id="clear-searches">Clear</a>
    </div>
  </div>
  <div >Favorite Tracks
    <i ></i>
    <div id="favorite-tracks-dropdown" >
      <a id="clear-favorites">Clear</a>
    </div>
  </div>
</nav>

CodePudding user response:

This is a simple implementation that I think might help you.

async function fetchMovie(movieTitle) {
  const apiUrl = `http://www.omdbapi.com/?t=${movieTitle}&plot=full&apikey=836f8b0`;

  let res = await fetch(apiUrl);
  res = await res.json();

  const title = res.Title;
  saveSearch(title); //   Should only pass the string:title
}

fetchMovie('spiderman');

function saveSearch(title) {
  if (!localStorage.getItem('movies')) localStorage.setItem('movies', ''); //   Initialize the localStorage

  //   e.g: (In localStorage)
  //   Avenger,Spiderman,The Antman etc..
  //   return this string & convert into an array

  let movies = localStorage
    .getItem('movies')
    .split(',')
    .filter((n) => n);

  //   Check if the title is already exists
  if (!movies.includes(title)) {
    movies.push(title);
  }

  //   Also store in localStorage as a string seperated by commas (,)
  movies = movies.join(',');

  localStorage.setItem('movies', movies);
}
  •  Tags:  
  • Related