简体   繁体   中英

JavaScript prevent Overwriting in localStorage

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));
}
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));
},

Bonus points:

Use Vuex to store your cart items, and the npm package vuex-persistesd-state to automatically sync the Vuex cart module with localStorage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM