mirror of
https://github.com/vercel/commerce.git
synced 2025-07-22 20:26:49 +00:00
Update item quantity
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
import { Trash } from '@components/icon'
|
||||
import { useCommerce } from '@lib/bigcommerce'
|
||||
import useUpdateItem from '@lib/bigcommerce/cart/use-update-item'
|
||||
import { useEffect, useState } from 'react'
|
||||
import formatVariantPrice from 'utils/format-item-price'
|
||||
import styles from './CartItem.module.css'
|
||||
|
||||
const CartItem = ({
|
||||
item,
|
||||
@@ -10,12 +13,35 @@ const CartItem = ({
|
||||
currencyCode: string
|
||||
}) => {
|
||||
const { locale } = useCommerce()
|
||||
const updateItem = useUpdateItem()
|
||||
const [quantity, setQuantity] = useState(item.quantity)
|
||||
const { price } = formatVariantPrice({
|
||||
listPrice: item.extended_list_price,
|
||||
salePrice: item.extended_sale_price,
|
||||
currencyCode,
|
||||
locale,
|
||||
})
|
||||
const handleBlur = async () => {
|
||||
const val = Number(quantity)
|
||||
|
||||
if (val !== item.quantity) {
|
||||
const data = await updateItem({
|
||||
itemId: item.id,
|
||||
item: {
|
||||
productId: item.product_id,
|
||||
variantId: item.variant_id,
|
||||
quantity: val,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// Reset the quantity state if the item quantity changes
|
||||
if (item.quantity !== quantity) {
|
||||
setQuantity(item.quantity)
|
||||
}
|
||||
}, [item.quantity])
|
||||
|
||||
console.log('ITEM', item)
|
||||
|
||||
@@ -27,8 +53,17 @@ const CartItem = ({
|
||||
<div className="py-2">
|
||||
<span>-</span>
|
||||
<input
|
||||
className="w-6 border-gray-300 border mx-3 rounded text-center text-sm"
|
||||
defaultValue="1"
|
||||
type="number"
|
||||
className={styles.quantity}
|
||||
value={quantity}
|
||||
onChange={(e) => {
|
||||
const val = Number(e.target.value)
|
||||
|
||||
if (Number.isInteger(val) && val >= 0) {
|
||||
setQuantity(e.target.value)
|
||||
}
|
||||
}}
|
||||
onBlur={handleBlur}
|
||||
/>
|
||||
<span>+</span>
|
||||
</div>
|
||||
|
Reference in New Issue
Block a user