mirror of
https://github.com/vercel/commerce.git
synced 2025-05-18 15:36:58 +00:00
feat: add core charge to cart
Signed-off-by: Chloe <pinkcloudvnn@gmail.com>
This commit is contained in:
parent
3bf7fa5af9
commit
d5cdb55845
@ -5,7 +5,7 @@ import { addToCart, createCart, getCart, removeFromCart, updateCart } from 'lib/
|
||||
import { revalidateTag } from 'next/cache';
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
export async function addItem(prevState: any, selectedVariantId: string | undefined) {
|
||||
export async function addItem(prevState: any, selectedVariantIds: Array<string>) {
|
||||
let cartId = cookies().get('cartId')?.value;
|
||||
let cart;
|
||||
|
||||
@ -19,12 +19,15 @@ export async function addItem(prevState: any, selectedVariantId: string | undefi
|
||||
cookies().set('cartId', cartId);
|
||||
}
|
||||
|
||||
if (!selectedVariantId) {
|
||||
if (!selectedVariantIds.length) {
|
||||
return 'Missing product variant ID';
|
||||
}
|
||||
|
||||
try {
|
||||
await addToCart(cartId, [{ merchandiseId: selectedVariantId, quantity: 1 }]);
|
||||
await addToCart(
|
||||
cartId,
|
||||
selectedVariantIds.map((variantId) => ({ merchandiseId: variantId, quantity: 1 }))
|
||||
);
|
||||
revalidateTag(TAGS.cart);
|
||||
} catch (e) {
|
||||
return 'Error adding item to cart';
|
||||
|
@ -4,6 +4,7 @@ import { ShoppingCartIcon } from '@heroicons/react/24/outline';
|
||||
import clsx from 'clsx';
|
||||
import { addItem } from 'components/cart/actions';
|
||||
import LoadingDots from 'components/loading-dots';
|
||||
import { CORE_VARIANT_ID_KEY } from 'lib/constants';
|
||||
import { ProductVariant } from 'lib/shopify/types';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useFormState, useFormStatus } from 'react-dom';
|
||||
@ -75,8 +76,13 @@ export function AddToCart({
|
||||
)
|
||||
);
|
||||
const selectedVariantId = variant?.id || defaultVariantId;
|
||||
const missingCoreVariantId = variant?.coreVariantId && !searchParams.has('coreVariantId');
|
||||
const actionWithVariant = formAction.bind(null, selectedVariantId);
|
||||
const missingCoreVariantId = variant?.coreVariantId && !searchParams.has(CORE_VARIANT_ID_KEY);
|
||||
|
||||
const coreVariantId = searchParams.get(CORE_VARIANT_ID_KEY);
|
||||
|
||||
const selectedVariantIds = [coreVariantId, selectedVariantId].filter(Boolean) as string[];
|
||||
|
||||
const actionWithVariant = formAction.bind(null, selectedVariantIds);
|
||||
|
||||
return (
|
||||
<form action={actionWithVariant}>
|
||||
|
Loading…
x
Reference in New Issue
Block a user