feat(poc): improve addToCart, remove warn

This commit is contained in:
Björn Meyer 2023-07-24 11:41:20 +02:00
parent 0bd4c18958
commit 66343b5e73
3 changed files with 18 additions and 4 deletions

View File

@ -104,7 +104,11 @@ export default async function ProductPage({ params }: { params: { handle: string
<Prose className="mb-6 text-sm leading-tight" html={product.descriptionHtml} /> <Prose className="mb-6 text-sm leading-tight" html={product.descriptionHtml} />
) : null} ) : null}
<AddToCart product={product} variants={product.variants} availableForSale={true} /> <AddToCart
product={product}
variants={product.variants}
availableForSale={product.availableForSale}
/>
</div> </div>
</div> </div>
<Suspense> <Suspense>

View File

@ -2,7 +2,7 @@
import { ApiClientError } from '@shopware/api-client'; import { ApiClientError } from '@shopware/api-client';
import { getApiClient } from 'lib/shopware/api'; import { getApiClient } from 'lib/shopware/api';
import { ExtendedCart } from 'lib/shopware/api-extended'; import { ExtendedCart, ExtendedLineItem } from 'lib/shopware/api-extended';
import { cookies } from 'next/headers'; import { cookies } from 'next/headers';
export const fetchCart = async function (cartId?: string): Promise<ExtendedCart | undefined> { export const fetchCart = async function (cartId?: string): Promise<ExtendedCart | undefined> {
@ -29,12 +29,23 @@ export const addItem = async (variantId: string | undefined): Promise<Error | un
} }
try { try {
let quantity = 1;
const apiClient = getApiClient(cartId); const apiClient = getApiClient(cartId);
// this part allows us to click multiple times on addToCart and increase the qty with that
const cart = await fetchCart(cartId);
const itemInCart = cart?.lineItems?.filter((item) => item.id === variantId) as
| ExtendedLineItem
| undefined;
if (itemInCart && itemInCart.quantity) {
quantity = itemInCart.quantity + 1;
}
apiClient.invoke('addLineItem post /checkout/cart/line-item', { apiClient.invoke('addLineItem post /checkout/cart/line-item', {
items: [ items: [
{ {
id: variantId, id: variantId,
quantity: 1, quantity: quantity,
referencedId: variantId, referencedId: variantId,
type: 'product' type: 'product'
} }

View File

@ -39,7 +39,6 @@ export default function CartModal({ cart, cartIdUpdated }: { cart: Cart; cartIdU
}, [setCookie, cartIdUpdated, cart.id]); }, [setCookie, cartIdUpdated, cart.id]);
useEffect(() => { useEffect(() => {
console.warn('cart modal', cart);
// Open cart modal when when quantity changes. // Open cart modal when when quantity changes.
if (cart.totalQuantity !== quantityRef.current) { if (cart.totalQuantity !== quantityRef.current) {
// But only if it's not already open (quantity also changes when editing items in cart). // But only if it's not already open (quantity also changes when editing items in cart).