mirror of
https://github.com/vercel/commerce.git
synced 2025-07-23 04:36:49 +00:00
Added useRemoveItem and other fixes
This commit is contained in:
@@ -2,6 +2,7 @@ import React, { FC, useState } from 'react'
|
||||
import cn from 'classnames'
|
||||
import type { ProductNode } from '@lib/bigcommerce/api/operations/get-all-products'
|
||||
import useAddItem from '@lib/bigcommerce/wishlist/use-add-item'
|
||||
import useRemoveItem from '@lib/bigcommerce/wishlist/use-remove-item'
|
||||
import useWishlist from '@lib/bigcommerce/wishlist/use-wishlist'
|
||||
import useCustomer from '@lib/bigcommerce/use-customer'
|
||||
import { Heart } from '@components/icons'
|
||||
@@ -19,19 +20,21 @@ const WishlistButton: FC<Props> = ({
|
||||
...props
|
||||
}) => {
|
||||
const addItem = useAddItem()
|
||||
const removeItem = useRemoveItem()
|
||||
const { data } = useWishlist()
|
||||
const { data: customer } = useCustomer()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const { openModal, setModalView } = useUI()
|
||||
const isInWishlist = data?.items?.some(
|
||||
const itemInWishlist = data?.items?.find(
|
||||
(item) =>
|
||||
item.product_id === productId &&
|
||||
item.variant_id === variant?.node.entityId
|
||||
)
|
||||
|
||||
const addToWishlist = async (e: any) => {
|
||||
const handleWishlistChange = async (e: any) => {
|
||||
e.preventDefault()
|
||||
setLoading(true)
|
||||
|
||||
if (loading) return
|
||||
|
||||
// A login is required before adding an item to the wishlist
|
||||
if (!customer) {
|
||||
@@ -39,11 +42,17 @@ const WishlistButton: FC<Props> = ({
|
||||
return openModal()
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
await addItem({
|
||||
productId,
|
||||
variantId: variant?.node.entityId!,
|
||||
})
|
||||
if (itemInWishlist) {
|
||||
await removeItem({ id: itemInWishlist.id! })
|
||||
} else {
|
||||
await addItem({
|
||||
productId,
|
||||
variantId: variant?.node.entityId!,
|
||||
})
|
||||
}
|
||||
|
||||
setLoading(false)
|
||||
} catch (err) {
|
||||
@@ -55,9 +64,9 @@ const WishlistButton: FC<Props> = ({
|
||||
<button
|
||||
{...props}
|
||||
className={cn({ 'opacity-50': loading }, className)}
|
||||
onClick={addToWishlist}
|
||||
onClick={handleWishlistChange}
|
||||
>
|
||||
<Heart fill={isInWishlist ? 'white' : 'none'} />
|
||||
<Heart fill={itemInWishlist ? 'white' : 'none'} />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
Reference in New Issue
Block a user