javascriptangularlocal-storageangular-local-storage

Overwriting problem in localstorage angular


I have a problem with my project, I am trying to add different recipes in localStorage when I press an Add to favourite button, but if I click on 3 different recipes, they overwrite in localStorage instead of adding each one of them. I would like some help here if someone can have a little bit of time. Thank you so much

recipe.ts. - I have here the recipes from my backend, I fetch them and try to add them in localStorage

ngOnInit() {
    this.getDataFromApi();
  }

  getDataFromApi() {
    this.service.getData().subscribe(
      (response) => {
        console.log('Response from API is', response);
        this.data = response;
      },
      (error) => {
        console.log('Error is', error);
      }
    );
  }

add(i: any) {
    localStorage.setItem('Recipe', JSON.stringify(this.data[i]));
    console.log('Added in localstorage' + i);

    if (localStorage.getItem('Recipe') === null) {
      alert('TEST');
    }
  }

  remove() {
    localStorage.removeItem('Recipe');
    console.log('I deleted from localStorage');
  }

HTML

<div *ngFor="let recipe of data; let i = index">
      <p>
        {{ recipe.title }}
      </p>
      <img src="{{ recipe.image }}" alt="" />
      <p>{{ recipe.description }}</p>
      <p>{{ recipe.calories }}</p>
      <p>{{ recipe.cookingTime }}</p>
      <p>{{ recipe._id }}</p>
      <button (click)="add(i)">Add to favorite</button>
      <button (click)="remove()">Remove from favorite</button>
    </div>

Right now if I press on Add to favourite I can see the recipe in localStorage but if I press on another Add to fav, the recipe that existed is overwritten with the new one. How can I solve to have them all in localStorage without overwriting? Thanks a lot


Solution

  • As per current implementation it will always override the localStorage value with latest one, normally localStorage store any data with a key & value, in your case whenever you are trying to add to fav you always passing one key, so that's why it override with latest one.

    I have modified your code, please have a look, Hope it will help you

    ADD METHOD

    add(i: any) {
      let recipes = JSON.parse(localStorage.getItem("Recipe")) || [];
      recipes.push(this.data[i]); 
      localStorage.setItem('Recipe', JSON.stringify(recipes));
      console.log('Added in localstorage' + i);
    
      if (localStorage.getItem('Recipe') === null) {
        alert('TEST');
      }
    }
    

    Might be possible you may facing issue with remove item, please have look to

    HTML CODE

    <div *ngFor="let recipe of data; let i = index">
      <p>
        {{ recipe.title }}
      </p>
      <img src="{{ recipe.image }}" alt="" />
      <p>{{ recipe.description }}</p>
      <p>{{ recipe.calories }}</p>
      <p>{{ recipe.cookingTime }}</p>
      <p>{{ recipe._id }}</p>
      <button (click)="add(i)">Add to favorite</button>
      <!-- pass this  recipe object with remove method -->
      <button (click)="remove(recipe)">Remove from favorite</button>
      
    </div>
    

    REMOVE METHOD

    remove(recipe) {
      let recipes = JSON.parse(localStorage.getItem("Recipe")) || [];
      if(recipes.length){
        recipes = recipes.filter((x:any) => x._id !== recipe._id); // this will remove the item from list
        localStorage.setItem('Recipe', JSON.stringify(recipes));
        console.log('I deleted from localStorage');
      } 
    }