fix(product): fix cart deduplication for products without variants
addToCart() compared item.variantId === selectedVariant where selectedVariant is null but saved items store variantId: undefined. null !== undefined caused findIndex to never match, always inserting a duplicate instead of incrementing quantity. Normalised with || undefined.
This commit is contained in:
@@ -54,7 +54,7 @@ export default function ProductDetailPage() {
|
||||
const cart = JSON.parse(localStorage.getItem('cart') || '[]')
|
||||
const existingIndex = cart.findIndex(
|
||||
(item: { productId: string; variantId?: string }) =>
|
||||
item.productId === product.id && item.variantId === selectedVariant
|
||||
item.productId === product.id && item.variantId === (selectedVariant || undefined)
|
||||
)
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
@@ -249,7 +249,12 @@ export default function ProductDetailPage() {
|
||||
size="lg"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
addToCart()
|
||||
const cart = JSON.parse(localStorage.getItem('cart') || '[]')
|
||||
const alreadyInCart = cart.some(
|
||||
(item: { productId: string; variantId?: string }) =>
|
||||
item.productId === product.id && item.variantId === (selectedVariant || undefined)
|
||||
)
|
||||
if (!alreadyInCart) addToCart()
|
||||
router.push('/cart')
|
||||
}}
|
||||
>
|
||||
|
||||
Reference in New Issue
Block a user