I'm struggling to retrieve the JSON string from localStorage
and add a new dish to it. It's not functioning correctly, can anyone lend me a hand? I am utilizing TypeScript
.
interface Dish {
id: number;
name: string;
desc: string;
price: number;
};
export class BasketService {
private BASKET: string = 'basket';
log(dish: Dish) {
var dishList: Dish[] = [];
if (!localStorage.getItem(this.BASKET)) {
dishList.push(dish); //push the first dish (if local storage is empty)
}
//Append an injected dish to the existing local storage.
dishList.push(JSON.parse(localStorage.getItem(this.BASKET)));
dishList.push(dish);
localStorage.setItem(this.BASKET, JSON.stringify(dishList));
}
}
Expected outcome: The dish should be successfully appended and stored in localStorage for future use.