Overwriting problem in localstorage angular

1.2k Views Asked by At

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

2

There are 2 best solutions below

3
Suneel Kumar On BEST ANSWER

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');
  } 
}
2
west efan On

localStorage is just a simple key value store, each time you call localStorage.setItem('Recipe', ...) a new value is assigned to the key "Recipe" similar to a variable assignment. If you want to store multiple Recipes in localStorage you can store all values as an array instead and each time you add a new value you fetch your previously stored values and push your new recipe in that array. Here is a possible solution

const recipes = JSON.parse(localStorage.getItem("Recipes")) || [];
recipes.push(this.data[i]);
localStorage.setItem("Recipes", JSON.stringify(recipes));

If you want to store a bunch of data locally in a more robust way I can also recommend the use of IndexedDB: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API and/or a library which handles locally stored data such as https://github.com/pouchdb/pouchdb