Added useRemoveItem and other fixes

This commit is contained in:
Luis Alvarez
2020-10-26 18:25:35 -05:00
parent 2cd41ee135
commit 0f4f061cbd
8 changed files with 68 additions and 33 deletions

View File

@@ -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>
)
}