Skip to content
Advertisement

Update quantity of items in cart without pushing entirety of object in JS

I’m having a bit of trouble with this problem. I’m working on the project of an e-commerce application that works on several html pages. I managed to push products through the cart html page, but I can’t seem to find a way to update on this page only the quantity of a product and not push every elements of said product (images, id, etc). Onclick, if product exists, I only want quantity to be updated. Here’s the code if any of you can help me out that’d be greatly appreciated.

setItems(kanap);

function setItems(kanap) {

  let cart = JSON.parse(localStorage.getItem('cart'));

  let imgKanap = kanap.imageUrl;
  let idKanap = kanap._id;
  let colorKanap = colors.value;
  let quantityKanap = parseInt(quantity.value);
  let key = idKanap + ' ' + colorKanap;

  let cartItem = {
    id: idKanap,
    color: colorKanap,
    quantity: quantityKanap,
    kanap: kanap
  };

  if (cart === null) {
    cart = [];
  }

  cart.push(cartItem);

  localStorage.setItem('cart', JSON.stringify(cart));

  function addProduct(cartItem) {
    var found = false;
    for (key in cartItem) {
      if (cartItem[key].idKanap == idKanap) {
        cartItem[key].quantityKanap += quantityKanap;
        found = true;
        break;
      }
    }
    if (!found) {
      cart.push(cartItem);
    }
  }
  addProduct();
}
<div class="item__content__addButton">
  <button id="addToCart" type="submit">Ajouter au panier</button>
</div>

<section class="cart">
  <!-- <section id="cart__items">
         <article class="cart__item" data-id="{product-ID}">
            <div class="cart__item__img">
              <img id ="image" alt="Photographie dun canapé">
            </div>
            <div class="cart__item__content">
              <div class="cart__item__content__titlePrice">
                <h2 class=title></h2>
                <p class =price></p>
              </div>
              <div class="cart__item__content__settings">
                <div class="cart__item__content__settings__quantity">
                  <p class= quantity>Qté : </p>
                  <input type="number" class="itemQuantity" name="itemQuantity" min="1" max="100" value="">
                </div>
                <div class="cart__item__content__settings__delete">
                  <p class="deleteItem">Supprimer</p>
                </div>
              </div>
            </div>
        </article> -->
</section>

Advertisement

Answer

There’s a few approaches you can take, but I am using .find to look through your cart.

If the .find() function finds an item with the same id as you’re about to add, it will up the quantity of the existing item instead of appending another object with the same ID.

I used a mock local storage since local storage doesn’t work in these snippets so just ignore that and use what you’ve been doing for local storage access.

let mockLS = null;

// guessed at the structure here, you may have something slightly different
const exampleItem = {
  _id: "abc",
  imageUrl: "imageurlexample",
  colors: {
    value: "red"
  },
  quantity: {
    value: 1
  }
}

const exampleItem2 = {
  _id: "abc2",
  imageUrl: "imageurlexample2",
  colors: {
    value: "blue"
  },
  quantity: {
    value: 1
  }
}

function setItems(kanap) {

  //let cart = JSON.parse(localStorage.getItem('cart'));

  // using a mock localstorage here since it doesn't work within this snippet, use what you currently have instead
  let cart = mockLS;

  let imgKanap = kanap.imageUrl;
  let idKanap = kanap._id;
  let colorKanap = kanap.colors.value;
  let quantityKanap = parseInt(kanap.quantity.value);
  let key = idKanap + ' ' + colorKanap;

  let cartItem = {
    id: idKanap,
    color: colorKanap,
    quantity: quantityKanap
    //kanap: kanap not sure why you want the whole obj here so I left this one out
  };

  if (cart === null) {
    cart = [];
  }

  // here is the case where cart exists and there may be the same item in it
  const itemExists = cart.find(item => {
    if(item.id === idKanap) {
      item.quantity += quantityKanap;
      return true;
    }
    return false;
  })

  if (!itemExists) {
    cart.push(cartItem);
  }

  //localStorage.setItem('cart', JSON.stringify(cart));
  mockLS = cart;
}

setItems(exampleItem);
setItems(exampleItem2);
setItems(exampleItem);

console.log(mockLS)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement