adrianhajdin / ecommerce_sanity_stripe

Modern Full Stack ECommerce Application with Stripe
https://jsmastery.pro
2.21k stars 675 forks source link

updated toggleCartItemQuantity function #68

Open Jared-Jianbin opened 2 years ago

Jared-Jianbin commented 2 years ago

Fixed the quantity change position issue in the cart, the position is changed because the index of product changed in the array, I used map to return them in the same order.

vercel[bot] commented 2 years ago

Someone is attempting to deploy a commit to a Personal Account owned by @adrianhajdin on Vercel.

@adrianhajdin first needs to authorize it.

mcjosh-sys commented 2 years ago

Fix for toggleCartItemQuantity changing the order of product in cart

const toggleCartItemQuantity = (id, action) => { foundProduct = cartItems.find(item => item._id === id) index = cartItems.findIndex(product => product._id === id) const currCartItem = cartItems.filter(item => item._id !== id)

  if(action === 'inc'){
        currCartItem.splice(index, 0, {...foundProduct, quantity: foundProduct.quantity+1})
        setCartItems(currCartItem)
        setTotalPrice(prevTotalPrice => prevTotalPrice + foundProduct.price)
        setTotalQuantities(prevTotalQuantities => prevTotalQuantities + 1)
  }else if(action === 'dec'){
      if(foundProduct.quantity > 1){
        currCartItem.splice(index, 0, {...foundProduct, quantity: foundProduct.quantity-1})
        setCartItems(currCartItem)
        setTotalPrice (prevTotalPrice => prevTotalPrice - foundProduct.price)
        setTotalQuantities(prevTotalQuantities => prevTotalQuantities - 1)
      }
  }

}

kko3ch commented 2 years ago

Merge