From 62efd1afc02422545579c529cd954d0c157889ee Mon Sep 17 00:00:00 2001
From: Rafi Zadanly <zadanlyr@gmail.com>
Date: Sat, 18 Mar 2023 10:17:16 +0700
Subject: navbar user dropdown, add to cart

---
 src/lib/product/components/ProductDesktop.jsx | 36 +++++++++++++++++++++++++--
 1 file changed, 34 insertions(+), 2 deletions(-)

(limited to 'src/lib/product/components/ProductDesktop.jsx')

diff --git a/src/lib/product/components/ProductDesktop.jsx b/src/lib/product/components/ProductDesktop.jsx
index 1272237b..f37d900c 100644
--- a/src/lib/product/components/ProductDesktop.jsx
+++ b/src/lib/product/components/ProductDesktop.jsx
@@ -6,6 +6,8 @@ import { HeartIcon } from '@heroicons/react/24/outline'
 import { Fragment, useEffect, useRef, useState } from 'react'
 import LazyLoad from 'react-lazy-load'
 import ProductSimilar from './ProductSimilar'
+import { toast } from 'react-hot-toast'
+import { updateItemCart } from '@/core/utils/cart'
 
 const ProductDesktop = ({ product, wishlist, toggleWishlist }) => {
   const [variantQuantity, setVariantQuantity] = useState(null)
@@ -34,6 +36,28 @@ const ProductDesktop = ({ product, wishlist, toggleWishlist }) => {
     }
   }
 
+  const validAction = (variantId) => {
+    let isValid = true
+    if (
+      !variantQuantity[variantId] ||
+      variantQuantity[variantId] < 1 ||
+      isNaN(parseInt(variantQuantity[variantId]))
+    ) {
+      toast.error('Jumlah barang minimal 1')
+      isValid = false
+    }
+    return isValid
+  }
+
+  const handleAddToCart = (variantId) => {
+    if (!validAction(variantId)) return
+    updateItemCart({
+      productId: variantId,
+      quantity: variantQuantity[variantId]
+    })
+    toast.success('Berhasil menambahkan ke keranjang')
+  }
+
   const productSimilarQuery = [
     product?.name.replace(/[()/"&]/g, ''),
     `fq=-product_id:${product.id}`,
@@ -168,8 +192,16 @@ const ProductDesktop = ({ product, wishlist, toggleWishlist }) => {
                       />
                     </td>
                     <td className='flex gap-x-3'>
-                      <button className='flex-1 py-2 btn-yellow'>Keranjang</button>
-                      <button className='flex-1 py-2 btn-solid-red'>Beli</button>
+                      <button
+                        type='button'
+                        onClick={() => handleAddToCart(variant.id)}
+                        className='flex-1 py-2 btn-yellow'
+                      >
+                        Keranjang
+                      </button>
+                      <button type='button' className='flex-1 py-2 btn-solid-red'>
+                        Beli
+                      </button>
                     </td>
                   </tr>
                 ))}
-- 
cgit v1.2.3

