import { ChangeEvent, useEffect, useState } from 'react' import cn from 'classnames' import Image from 'next/image' import Link from 'next/link' import s from './CartItem.module.css' import { Trash, Plus, Minus } from '@components/icons' import { useUI } from '@components/ui/context' import type { LineItem } from '@framework/types' import usePrice from '@framework/product/use-price' import useUpdateItem from '@framework/cart/use-update-item' import useRemoveItem from '@framework/cart/use-remove-item' type ItemOption = { name: string nameId: number value: string valueId: number } const CartItem = ({ item, currencyCode, ...rest }: { item: LineItem currencyCode: string }) => { const { closeSidebarIfPresent } = useUI() const { price } = usePrice({ amount: item.variant.price * item.quantity, baseAmount: item.variant.listPrice * item.quantity, currencyCode, }) const updateItem = useUpdateItem(item) const removeItem = useRemoveItem() const [quantity, setQuantity] = useState(item.quantity) const [removing, setRemoving] = useState(false) const updateQuantity = async (val: number) => { await updateItem({ quantity: val }) } const handleQuantity = (e: ChangeEvent) => { const val = Number(e.target.value) if (Number.isInteger(val) && val >= 0) { setQuantity(Number(e.target.value)) } } const handleBlur = () => { const val = Number(quantity) if (val !== item.quantity) { updateQuantity(val) } } const increaseQuantity = (n = 1) => { const val = Number(quantity) + n if (Number.isInteger(val) && val >= 0) { setQuantity(val) updateQuantity(val) } } const handleRemove = async () => { setRemoving(true) try { // If this action succeeds then there's no need to do `setRemoving(true)` // because the component will be removed from the view await removeItem(item) } catch (error) { setRemoving(false) } } // TODO: Add a type for this const options = (item as any).options useEffect(() => { // Reset the quantity state if the item quantity changes if (item.quantity !== Number(quantity)) { setQuantity(item.quantity) } }, [item.quantity]) return (
  • {item.variant.image!.altText}
    closeSidebarIfPresent()} > {item.name} {options && options.length > 0 ? (
    {options.map((option: ItemOption, i: number) => ( {option.value} {i === options.length - 1 ? '' : ', '} ))}
    ) : null}
    {price}
  • ) } export default CartItem