Denis L
Denis L

Reputation: 121

Change state in localstorage

I have problem with changing data in localstorage. I am making cart and i have a lot of products. After clicking "add to cart" in product page, data checks if localstorage already has this product, so if it is true, product is not adding it just changes count state. All is working until the moment when i am adding another product. After this, when i want so add product that is already in localstorage it has to change count state, but it adds one more time this product. Why? Can you help me please.

0: {titleProduct: "first", productPrice: "15", count: 2}
1: {titleProduct: "second"", productPrice: "9", count: 3}
2: {titleProduct: "first", productPrice: "15", count: "1"}

but it should look like this

0: {titleProduct: "first", productPrice: "15", count: 3}
1: {titleProduct: "second"", productPrice: "9", count: 3}

Code:

  const rawData = localStorage.getItem("cart") || "[]";
const data = JSON.parse(rawData);
var setData;

data.filter(titleNow => {
  if (titleNow.titleProduct == titleProduct) {
  setData = true;
  }
  else {
    setData = false;
  }
});


  if (setData) {
   data.filter(item => {
    item.titleProduct == titleProduct ? item.count = parseInt(item.count)+Number(dataCart.innerHTML) : "";
})
  } else {


    data.push({titleProduct, productPrice, count: dataCart.innerHTML});
   

  }

  localStorage.setItem("cart", JSON.stringify(data));

Upvotes: 0

Views: 50

Answers (2)

Al Hill
Al Hill

Reputation: 479

You can try with something like this

const updatedCart = data.map(item => {
    if(titleProduct === item.titleProduct){
        return {
            ...item,
            count: dataCart.innerHTML
        }
    }
    else{
        return item
    }
})

localStorage.setItem("cart", JSON.stringify(updatedCart));

Iterates over data and changes the count for dataCart.innerHTML if titleProduct concurs with the iteratee

Upvotes: 0

Yousaf
Yousaf

Reputation: 29282

filter is not the right function to use here. Use .find() or .findIndex()

Problem in your code is that setData variable is set depending on whether the last product's title is equal to titleProduct or not. If it is, setData will be set to true otherwise it will be false. So if you had tried to add the third product with the title second, your code would have worked.

const product = data.find(prod => prod.titleProduct === titleProduct);

if (prod) {
   prod.count++;
} else {
   data.push({titleProduct, productPrice, count: dataCart.innerHTML});
}

localStorage.setItem("cart", JSON.stringify(data));

Upvotes: 3

Related Questions