0

I am creating a javascript cart.

Here's how I add a product to the cart:

function addToCart(id, qty){    
    var basket = []
    basket.push({
        product_id: id,
        quantity: qty
    });
    localStorage.setItem('basket', JSON.stringify(basket));
}

Now if id is already there, I am trying only to update current basket from localStorage

When I add the same product id, it's duplicating it.

[{"product_id":"10", "quantity":"1"}, {"product_id":"10", "quantity":"1"}]

I want to increase only quantity like:

[{"product_id":"10", "quantity":"2"}]

Tried few methods with each and for with no luck :(

Any help please?

4 Answers 4

4

You're replacing your stored array every time, which won't have the problem you've described unless you don't really have the var basket = [] in your function. But the problem you've described would be caused by not checking for an existing entry with the product ID.

Instead:

  1. Keep your array in memory, not just local storage
  2. Load it from local storage on page load
  3. Update it in local storage when you change your memory copy
  4. Remove it from local storage when the user completes their purchase or clears their basket

For #1 and #2: In a place that's global to your code (but ideally not really global):

var basket = JSON.parse(localStorage.getItem("basket")) || [];

For #3:

function rememberBasket() {
    localStorage.setItem('basket', JSON.stringify(basket));
}
function addToCart(id, qty){
    // See if product exists
    var entry = basket.find(function(e) { return e.product_id == id; });
    if (entry) {
        entry.quantity += qty; // Or just `= qty` to replace rather than adding
    } else {
        basket.push({
            product_id: id,
            quantity: qty
        });
    }
    rememberBasket();
}

For #4, of course:

basket = [];
rememberBasket();

Your original code was all ES5 and earlier, so I stuck to that above, but ES2015+ features would make it more concise.

Sign up to request clarification or add additional context in comments.

2 Comments

not good. is always pushing not updating, i did a fiddle here jsfiddle.net/templatetuners/ox8cgueh
@Adrian - I'm so used to arrow functions I forgot the return in the find callback. Fixed.
1

Solution :

function addToCart(id, qty) {
    var newItem = true;
    var basket = json.parse(localStorage.getItem('basket'));
    basket.forEach(function (item){
        if(item.product_id == id) {
            item.quantity += qty;
            newItem = false;
        }
    })
    if(newItem) {
        basket.push({
           product_id: id,
           quantity: qty
        });
        localStorage.setItem('basket', JSON.stringify(basket));
    }
}

3 Comments

quantity returns 11 instead of 2 (1+1), any ideea why? thanks.
@Adrian - forEach is the wrong tool here, no need to keep going once you've found the item.
he needs to update the quantity field if the id already exist
1

First, you need to try to read the basket out of localStorage instead of starting with an empty array each time. Second, I'd recommend you use an object instead of an array. Your products already have ids, so instead of searching the array each time, just let the language do the key lookup for you. Last, you're missing any treatment of how to update existing items in the cart. Here's how I'd approach that, supporting both adding new items to the cart, and increasing the quantity of existing items.

function addToCart(id, qty){    
    var basket = JSON.parse(localStorage.getItem('basket')) || {};
    if (basket[id]) {
      basket[id] += qty;
    } else {
      basket[id] = qty;
    }
    localStorage.setItem('basket', JSON.stringify(basket));
    console.log(basket);
}

addToCart(1,1);
addToCart(2,1);
addToCart(1,1);
addToCart(3,2);
addToCart(3,1);

// results in:
VM222:9 {1: 1}
VM222:9 {1: 1, 2: 1}
VM222:9 {1: 2, 2: 1}
VM222:9 {1: 2, 2: 1, 3: 2}
VM222:9 {1: 2, 2: 1, 3: 3}

Comments

0

Try this

function addToCart(id, qty){    
   var basket = JSON.parse(localStorage.getItem('basket'));
   var isExists = false;
    if(basket === null || basket === undefined){
     basket = [];
   }

    basket.reduce(function(o,i){
       if(i.product_id === id){
          i.quantity += qty;isExists = true;
        }
        o.push(i);
       return o;
    },[]);
    if(!isExists){


    basket.push({
        product_id: id,
        quantity: qty
    });}
    localStorage.setItem('basket', JSON.stringify(basket));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.