Q
Q
qfrontend2019-05-20 22:08:22
JavaScript
qfrontend, 2019-05-20 22:08:22

How to remove duplicate items in cart but increase their count in React-Redux?

Greetings) I made a basket on the site on React-Redux .
On click, an action is called , the parameter of which is the object of the product being added.
Next, the product object is pushed into an array. Then this array is written to localStorage .
How to organize the removal of duplicate products and simply increase their number?
Thank you)

export const ADD_PRODUCT = "ADD_PRODUCT";
let basket = [];
let sum = 0;

const addProduct = product => {
  // Если localStorage не пустой, то взять значения из него
  if (localStorage.getItem("basket") !== null) {
    basket = JSON.parse(localStorage.basket);
    sum = JSON.parse(localStorage.sum);
    sum.toFixed(1);
  }
  // Если action передан параметр-(добавляемый товар), то добавить его
  if (product) {
    basket.push(product);
    sum += product.price;
  }
  // Переписать localStorage
  localStorage.setItem("basket", JSON.stringify(basket));
  localStorage.setItem("sum", JSON.stringify(sum));
  return dispatch => {
    dispatch({
      type: ADD_PRODUCT,
      payload: {
        basket: basket,
        sum: sum
      }
    });
  };
};

export default addProduct;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-05-21
@qfrontend

1. Why every addition check the existence of the basket in localStorage? Add an initBasket action and call it once during application initialization:

let cart = [];
// сумму тут хранить не надо

const initCart = () => {/* ... */};
const addProduct = (product, quantity)  => {/* ... */};
const deleteProduct = id => {/* ... */};
const changeQuantity = (id, quantity) => {/* ... */};

2. The amount must be recalculated after each operation again. No calculations based on previous results.
3. Update Quantity:
const addProduct = (product, quantity) => {
  const index = cart.indexOf(item => item.product.id = product.id);

  if (index !== -1) {
    cart = cart.map((item, i) =>
      i === index ? { ...item, quantity: item.quantity + quantity } : item);
  } else {
    cart = [ ...cart, { product, quantity} ];
  }
  
  const sum = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);

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

  return dispatch => {
    dispatch({
      type: ADD_PRODUCT,
      payload: {
        cart,
        sum,
      },
    });
  };
}

Note the update is immutable. If you are sure that you do not need immutability here, then replace the update with:
if (index !== -1) {
  cart[index].quantity += quantity;
} else {
  cart.push({ product, quantity });
}

cartItem structure:
{
  product,
  quantity,
}

R
Robur, 2019-05-21
@Robur

write down not just a product, but a product + quantity , and then, before pushing, check if there is already the same product, if there is, instead of .push write increase the count.

const productInBucket = bucket.find(item => /* проверить что item.product == product так как вам нужно*/)
if (productInBucket) productInBucket.count++
else basket.push({product, count: 1})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question