Home > Blockchain >  Avoid duplicates in the gif Store - Angular
Avoid duplicates in the gif Store - Angular

Time:10-04

enter image description hereI am creating a gif store using angular. I have a page with search input , when i write a gif name into it a giphy search api is called and it returns the gifs based on name. At the same time i have created a user Store where i am saving the gifs via localStorage. The gifs are object with url and id. I want to check if the gif coming from giphy api is already present in localStorage it should not be added in user Store(localStorage).

Below is the code

User-Gif.component - OnSeachClick method returns gifs from giphy api.

onSearchClick() : void {
    this.gs.searchGif(this.searchInput,this.defaultLimit).subscribe(res => {
      this.gifData = res.data;
    })
  }

addToStore method stores the gifs returned from giphy api in localStorage-

 addToStore(): void {
    let addGif= new Array<GifUrl>();
  
    this.gifData.forEach((i:any) => {
      addGif.unshift({
        id: i.id,
        url: i.images.original.url,
        date: new Date()
      })
      localStorage.setItem(this.searchInput.toUpperCase(),JSON.stringify(addGif));
   })
  
    this.getDataInStore();
    this.gifData = [];
    addGif=[];
    this.searchInput = '';
  }

getDataInStore methods gets the gifs from localStorage -

 getDataInStore():void {
    this.gifUrl=[];
    if(Object.keys(localStorage)) {
      Object.keys(localStorage).forEach((key:string)=> {
       let keyData:any[] = JSON.parse(localStorage.getItem(key) || '')
        this.gifUrl.push(...keyData);
     })
    }
  }

User-gif.html -

    <div >
        <app-user-store [gifData]="gifUrl" (filteredData)="getFilteredData($event)" (sortedData)="sortByDate()"
            (resetSearch)="resetData()">
        </app-user-store>
    </div>

CodePudding user response:

solution should be pretty simple:

isInLocalStorage(key:string):boolean{
  return localStorage.getItem(key) !== null;
}

before adding the element, check if it's already present

CodePudding user response:

Firstly, this condition: if(Object.keys(localStorage)) always evaluates to true. When localStorage is empty, Object.keys will return an empty array, which is 'truthy': https://developer.mozilla.org/en-US/docs/Glossary/Truthy.

Regards your question: you're currently storing the GifUrls in local storage as an array, and your 'key' for accessing localStorage is the search term.

It would be much more efficient to store the gifs in localStorage with the gif ID as the key.

By storing gifs in an array, Angular will need to search potentially every GifUrl array for the duplicate gif - a gif returned from searching 'like' could also be returned by searching 'love' for example, and Angular won't "know" beforehand which GifUrl arrays to search - it will have to check them all, each time a new search is made.

By storing each Gif by ID, checking for a duplicate will instead be a matter of checking by calling localStorage.getItem(gifID).

CodePudding user response:

You need to use Set in order to prevent from duplicate items before setting into the localStorage. something like this:

this.gifData.forEach((i:any) => {
      addGif.unshift({
        id: i.id,
        url: i.images.original.url,
        date: new Date()
      })
//This is new line that You want
let uniqueItems = Array.from(new Set(addGif));
      
localStorage.setItem(this.searchInput.toUpperCase(),JSON.stringify(uniqueItems));
   })
  • Related