4
0
forked from crowetic/commerce

Improve the UX of removing a product from the cart

This commit is contained in:
Luis Alvarez 2020-10-26 23:02:19 -05:00
parent ec9953790c
commit fbda3c68f8

View File

@ -1,11 +1,12 @@
import s from './CartItem.module.css'
import { ChangeEvent, useEffect, useState } from 'react'
import cn from 'classnames'
import Image from 'next/image'
import Link from 'next/link'
import { ChangeEvent, useEffect, useState } from 'react'
import { Trash, Plus, Minus } from '@components/icons'
import usePrice from '@lib/bigcommerce/use-price'
import useUpdateItem from '@lib/bigcommerce/cart/use-update-item'
import useRemoveItem from '@lib/bigcommerce/cart/use-remove-item'
import s from './CartItem.module.css'
const CartItem = ({
item,
@ -22,8 +23,9 @@ const CartItem = ({
const updateItem = useUpdateItem(item)
const removeItem = useRemoveItem()
const [quantity, setQuantity] = useState(item.quantity)
const [removing, setRemoving] = useState(false)
const updateQuantity = async (val: number) => {
const data = await updateItem({ quantity: val })
await updateItem({ quantity: val })
}
const handleQuantity = (e: ChangeEvent<HTMLInputElement>) => {
const val = Number(e.target.value)
@ -47,6 +49,17 @@ const CartItem = ({
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({ id: item.id })
} catch (error) {
setRemoving(false)
}
}
useEffect(() => {
// Reset the quantity state if the item quantity changes
@ -56,7 +69,11 @@ const CartItem = ({
}, [item.quantity])
return (
<li className="flex flex-row space-x-8 py-8">
<li
className={cn('flex flex-row space-x-8 py-8', {
'opacity-75 pointer-events-none': removing,
})}
>
<div className="w-16 h-16 bg-violet relative overflow-hidden">
<Image
className={s.productImage}
@ -96,10 +113,7 @@ const CartItem = ({
</div>
<div className="flex flex-col justify-between space-y-2 text-base">
<span>{price}</span>
<button
className="flex justify-end"
onClick={() => removeItem({ id: item.id })}
>
<button className="flex justify-end" onClick={handleRemove}>
<Trash />
</button>
</div>