diff --git a/components/product/BuyTogether/AddToCartButton/common.tsx b/components/product/BuyTogether/AddToCartButton/common.tsx new file mode 100644 index 0000000..f9fd65b --- /dev/null +++ b/components/product/BuyTogether/AddToCartButton/common.tsx @@ -0,0 +1,51 @@ +import Button from "$store/components/ui/Button.tsx"; +import { sendEvent } from "$store/sdk/analytics.tsx"; +import { useUI } from "$store/sdk/useUI.ts"; +import { AddToCartParams } from "apps/commerce/types.ts"; +import { useState } from "preact/hooks"; + +export interface Props { + /** @description: sku name */ + eventParams: AddToCartParams; + onAddItem: () => Promise; +} + +const useAddToCart = ({ eventParams, onAddItem }: Props) => { + const [loading, setLoading] = useState(false); + const { displayCart } = useUI(); + + const onClick = async (e: MouseEvent) => { + e.preventDefault(); + e.stopPropagation(); + + try { + setLoading(true); + + await onAddItem(); + + sendEvent({ + name: "add_to_cart", + params: eventParams, + }); + + displayCart.value = true; + } finally { + setLoading(false); + } + }; + + return { onClick, loading, "data-deco": "add-to-cart" }; +}; + +export default function AddToCartButton(props: Props) { + const btnProps = useAddToCart(props); + + return ( + + ); +} diff --git a/components/product/BuyTogether/AddToCartButton/vtex.tsx b/components/product/BuyTogether/AddToCartButton/vtex.tsx new file mode 100644 index 0000000..2755115 --- /dev/null +++ b/components/product/BuyTogether/AddToCartButton/vtex.tsx @@ -0,0 +1,18 @@ +import { useCart } from "apps/vtex/hooks/useCart.ts"; +import Button, { Props as BtnProps } from "./common.tsx"; + +export interface Props extends Omit { + products: Array<{ seller: string; id: string; quantity: number }>; +} + +function AddToCartButton({ products, eventParams }: Props) { + const { addItems } = useCart(); + const onAddItem = () => + addItems({ + orderItems: products, + }); + + return