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
As per current implementation it will always override the
localStoragevalue with latest one, normallylocalStoragestore any data with akey&value, in your case whenever you are trying toadd to favyou always passing onekey, 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
Might be possible you may facing issue with
remove item, please have look toHTML CODE
REMOVE METHOD