Home > Back-end >  Javascript is returning duplicate values
Javascript is returning duplicate values

Time:08-28

I am getting records from an movie API and then I am generating a radio button along each record and I want to collect all the selected items in an array and then I am storing that array in my local storage but the problem is it is always returning two duplicate value e.g. if I select avengers then it will store avengers for twice in array as well as in local storage is there any way I could fix this duplications:

const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
let arr=[];


showMovies(apiUrl);
function showMovies(url) {
  arr = [];
  fetch(url)
    .then((res) => res.json())
    .then(function (data) {
      data.results.forEach((element) => {
        let movYear = new Date(element.release_date);

        const el = document.createElement("div");
        const image = document.createElement("img");
        const title = document.createElement("h2");
        const year = document.createElement("h2");
        const rank = document.createElement("h2");
        const node = document.createTextNode("Favrouite: ")

        const wrapper = document.createElement("h2");
        const fav = document.createElement("INPUT");
        
        title.classList.add("title");
        fav.setAttribute("type", "radio");
        fav.setAttribute("id", element.id);
        fav.classList.add("fav")
        
        wrapper.insertBefore(node, wrapper.children[0]);
        wrapper.appendChild(fav);
        title.innerHTML = `Title:  ${element.title}`;
        year.innerHTML = `Release:  ${movYear.getFullYear()}`;
        rank.innerHTML = `Rating:  ${element.popularity}`;
        image.src = IMGPATH   element.poster_path;

        el.appendChild(image);
        el.appendChild(title);
        el.appendChild(year);
        el.appendChild(rank);

        el.appendChild(wrapper);
        main.appendChild(el);
        
      });
      let temp;
      main.addEventListener("click",function(e) {
        const tgt = e.target;
        if (tgt.matches(".fav")) {
          temp = tgt.closest("div").querySelector("h2.title").textContent;
          temp = temp.slice(6).trim();
          arr.push(temp);
          console.log(temp);
           localStorage.setItem('test', JSON.stringify(arr));
        }
      })
    });
}

console.log(arr)

// Retrieve the object from storage
// var retrievedObject = localStorage.getItem('test');
// console.log( retrievedObject);

let searchTerm;

form.addEventListener("submit", (e) => {
  e.preventDefault();
  main.innerHTML = "";

  searchTerm = search.value;
  
  if (searchTerm) {
    showMovies(SEARCHAPI   searchTerm)
      search.value = "";
    }
    else if(!searchTerm){
      showMovies(apiUrl)
    }
    else {
        main.innerHTML = "<h1>No result Found!</h1>";
    }

});

//API will return object like following:

0:
adult: false
backdrop_path: "/7ZO9yoEU2fAHKhmJWfAc2QIPWJg.jpg"
genre_ids: (3) [28, 878, 53]
id: 766507
original_language: "en"
original_title: "Prey"
overview: "When danger threatens her camp, the fierce and highly skilled Comanche warrior Naru sets out to protect her people. But the prey she stalks turns out to be a highly evolved alien predator with a technically advanced arsenal."
popularity: 7796.888
poster_path: "/ujr5pztc1oitbe7ViMUOilFaJ7s.jpg"
release_date: "2022-08-02"
title: "Prey"
video: false
vote_average: 8.1
vote_count: 2730

CodePudding user response:

The problem was duplicate function call once I was calling API function at very top to show some dummy movies on screen until user search something by his self and second when user enter any value in search and hit submit so what I have done to solve this problem is I created two separate functions and assign them individual functionality and hence problem solved.

  • Related