Reputation: 185
I am working on a Vue project and I am creating shopping cart. When you press on the button the item details are passed to localStorage and from within it is displayed in the shopping cart.
The problem is when I press on new product to put it in the cart - my key gets overwritten and because of that I can have only one item in the cart.
Related code:
tobakset(){
var size = this.ssize;
var color = this.scolor;
let obj = {s : size, c : color, n : this.link(this.links).name, id : this.link(this.links).id}
this.items.push(obj)
localStorage.setItem(STORAGE_KEY, JSON.stringify(this.items));
}
Upvotes: 1
Views: 505
Reputation: 27713
toBasket() {
const obj = {
s: this.ssize,
c: this.scolor,
n: this.link(this.links).name,
id: this.link(this.links).id,
};
this.items.push(obj);
const currentItems = localStorage.getItem(STORAGE_KEY) || '[]';
localStorage.setItem(
STORAGE_KEY,
JSON.stringify([...JSON.parse(currentItems), ...this.items])
);
},
This should work. Though it feels a bit wrong. If we're storing basket items in localStorage, you probably want to load those into the cart as soon as the appropriate component is created.
created() {
const currentItems = localStorage.getItem(STORAGE_KEY) || '[]';
this.items = JSON.parse(currentItems);
},
Now you can just do this for your toBasket()
method, because you just sync'd the cart with the stored items in localStorage:
toBasket() {
const obj = {
s: this.ssize,
c: this.scolor,
n: this.link(this.links).name,
id: this.link(this.links).id,
};
this.items.push(obj);
localStorage.setItem(STORAGE_KEY, JSON.stringify(this.items));
},
Use Vuex to store your cart items, and the npm package vuex-persistesd-state to automatically sync the Vuex cart module with localStorage.
Upvotes: 1