Skip to content
Advertisement

How to add an item to the cart

I don’t really understand this function, like what does the “cartItems.push(…product, count:1)” actually do? I am a begginer and it’s hard for me to understand these logic. It’d be kind of you guys to help me to explain! Thank you so much!

addToCart = (product) => {
    let alreadyIncart = false;
    const cartItems = this.state.cartItems.slice()
    cartItems.forEach((item) => {
      if(item.id===product.id){
        item++;
        alreadyIncart = true;
      }
      if(!alreadyIncart){
        cartItems.push(...product, count:1)
      }
    })
  }

Advertisement

Answer

Here’s a breakdown, step-by-step.

addToCart = (product) => {
  // Sets boolean value if item is in cart initially to false, not found
  let alreadyIncart = false;

  // slice creates a shallow copy of the cartItems array
  const cartItems = this.state.cartItems.slice();

  // Iterate the cartItems copy, calling a function for each element
  cartItems.forEach((item) => {
    // if there is a matching item id
    if (item.id === product.id) {
      // increment item count
      item++;
      // set found to true
      alreadyIncart = true;
    }

    // if item was not found in cart, 
    // add it to the cartItems array with an initial count value
    if (!alreadyIncart) {
      cartItems.push(...product, count:1)
    }
  })
}

There appears to be some issues with the code, however.

  1. item++ is mutating the existing item object. Generally mutations like this should be avoided. It’s also not valid since item is an object. It should update the count property, i.e. item.count++, or rather, count: item.count + 1 in a new object reference.
  2. cartItems.push(...product, count:1) is syntactically incorrect, it needs to be a single object, i.e. cartItems.push({ ...product, count: 1 }).

A more correct version would return a new array with updated values and not mutate any passed arguments.

addToCart = (product) => {
  const { cartItems } = this.state;

  // check if product is already in cart
  const isInCart = cartItems.some(item => item.id === product.id);

  if (isInCart) {
    // if already in cart, return shallow copy array
    // and shallow copy the matching item, then update
    // the count by 1
    return cartItems.map(item => item.id === product.id 
      ? { ...item, count: item.count + 1 }
      : item); // just return non-match
  } else {
     // Not in cart, just create item object with initial count 1
     // concat appends to and returns a new array
     return cartItems.concat({
       ...product,
       count: 1,
     });
  }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement