Search code examples
javascriptreactjslocal-storagecartreact-functional-component

Check for duplicates in a shopping cart and updating the quantity (ReactJS)


I have a shopping cart that is a nested list. I want to check if a certain item is already in the list before adding it again. If it is already in the list I just want to update the quantity. What am I doing wrong here, and how can I implement localstorage here (hypothetically)

Here is the function:

   function addToCart(e) {
    var updatedCart = [];
    if (cart.includes(e.target.innerText)) {
    console.log("Duplicate found");
    for (var i = 0; i < cart.length; i++) {
        if (cart[i][0] == e.target.innerText) {
        cart[i][1]++;
        updatedCart.push(cart[i]);
        i++;
        } else {
        i++;
        }
    }
    } else {
    setCart((cart) => [...cart, [e.target.innerText, 1]]);
    }
}

Solution

  • As a suggestion, it is better (time-complexity wise) to store something like your cart in a javascript object or a map. You could store your item names (it would be better to have some sort of unique id) as the keys, and the item amount as the value; so basically something like that:

    const cart = {
      itemA: 1,
      itemB: 2,
      itemC: 4
    }
    

    That way you could just update the value by copying the old state and overwrite only the value of the searched key if it exists

    const cartCopy = {...cart};
    if (!cartCopy[itemName]) {
      cartCopy[itemName] = 1;
    } else {
      cartCopy[itemName] += 1;
    }
    setState(cartCopy);
    

    You should improve that code by yourself and using this snippet just as some quick tip, as to use localStorage it would be not that hard. Especially with this object way of doing that; just remind that localStorage is slow to access, so I would suggest to update your component's state first, and when is updated just add into the localStorage your object with some kind of label. You should use localStorage only to have some kind of persistency of your cart through the sessions, so basically you'll load the state from localStorage only when you mount the app (if the cart is always visible) and update the localStorage when there is some update to the local state of your cart.