Background:
In an attempt to implement a "Favourites List" feature where users can add favorite categories with heart icons on the home page, I encountered challenges. Despite searching for a logical flow on Google, I couldn't find a helpful solution. To address this, I initially created a logic where clicking the heart button would check whether the section is already in the FavList
array, which currently only accepts one section as a prototype. While the heart buttons worked correctly, I faced the issue of the FavList
becoming empty after refreshing the page.
For example, in the vegetables section (food.component.html):
<div class="row">
<div class="col-10">
<h3 class="mb-3 d-inline">Vegetables
<button class="btn" (click)="addFavVeg()">
<i class="bi align-items-center border-0 text-danger" [ngClass]="favList.includes('vegetables') ? 'bi-heart-fill':'bi-heart'" id="vegetables"></i>
</button>
</h3>
</div>
In food.component.ts:
export class FoodComponent implements OnInit {
foodList: Product[]
favList: string[] = this.productsService.favList
addFavVeg() {
this.productsService.addFavVeg()
}
addFavFruits() {
this.productsService.addFavFruits()
}
constructor(private productsService: ProductsService) {}
ngOnInit() {
this.productsService.saveData('favList', JSON.stringify(this.favList))
this.productsService.getData('favList')
console.log(this.productsService.getData('favList'))
return this.productsService.findAllFood().subscribe(data => {
this.foodList = data
})
}
}
I made the decision to relocate functions to the service where local storage functionalities are located.
In products.service.ts:
export class ProductsService {
favList: string[] = []
addFavVeg() {
if (this.favList.includes('vegetables')) {
this.favList.pop();
}
else if (this.favList.length > 0){
this.favList.pop();
this.favList.push('vegetables');
}
else {
this.favList.push('vegetables');
}
this.saveData('favList', this.favList)
console.log(this.getData('favList'))
}
addFavFruits() {
if (this.favList.includes('fruits')) {
this.favList.pop();
}
else if (this.favList.length > 0){
this.favList.pop();
this.favList.push('fruits');
}
else {
this.favList.push('fruits');
}
this.saveData('favList', this.favList)
console.log(this.getData('favList'))
}
public saveData(key, value) {
localStorage.setItem(key, value)
}
public getData(key) {
JSON.parse(localStorage.getItem(key))
console.log(JSON.parse(localStorage.getItem(key)))
}
}
Upon checking the browser, the heart buttons remained functional. However, a console error was thrown preventing local storage from saving the added values to the array: the error
Despite further exploration into local storage usage, integrating it with my favList
concept remains a challenge.
Any suggestions or solutions?
When attempting to save the FavList array in local storage, I expected confirmation in the console showing the array with either 'vegetables' or 'fruits' value. Instead, I encountered an error related to JSON serialization.