mirror of
https://github.com/vercel/commerce.git
synced 2025-05-19 07:56:59 +00:00
add multiple items to cart at once
This commit is contained in:
parent
37a5e61ca0
commit
4ea96cc6e5
@ -3,7 +3,7 @@ import { notFound } from 'next/navigation';
|
|||||||
import { Suspense } from 'react';
|
import { Suspense } from 'react';
|
||||||
|
|
||||||
import clsx from 'clsx';
|
import clsx from 'clsx';
|
||||||
import { AddToCart } from 'components/cart/add-to-cart';
|
import { AddManyToCart } from 'components/cart/add-many-to-cart';
|
||||||
import { GridTileImage } from 'components/grid/tile';
|
import { GridTileImage } from 'components/grid/tile';
|
||||||
import Label from 'components/label';
|
import Label from 'components/label';
|
||||||
import { SupportedLocale } from 'components/layout/navbar/language-control';
|
import { SupportedLocale } from 'components/layout/navbar/language-control';
|
||||||
@ -135,7 +135,9 @@ export default async function ProductPage({
|
|||||||
<div className="max-w-sm">
|
<div className="max-w-sm">
|
||||||
<VariantSelector options={product.options} variants={product.variants} />
|
<VariantSelector options={product.options} variants={product.variants} />
|
||||||
|
|
||||||
<AddToCart
|
<AddManyToCart
|
||||||
|
product={product}
|
||||||
|
quantity={1}
|
||||||
variants={product.variants}
|
variants={product.variants}
|
||||||
availableForSale={product.availableForSale}
|
availableForSale={product.availableForSale}
|
||||||
/>
|
/>
|
||||||
|
@ -28,6 +28,37 @@ export const addItem = async (variantId: string | undefined): Promise<String | u
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const addItems = async ({
|
||||||
|
variantId,
|
||||||
|
quantity = 1
|
||||||
|
}: {
|
||||||
|
variantId: string | undefined;
|
||||||
|
quantity: number;
|
||||||
|
}): Promise<String | undefined> => {
|
||||||
|
let cartId = cookies().get('cartId')?.value;
|
||||||
|
let cart;
|
||||||
|
|
||||||
|
if (cartId) {
|
||||||
|
cart = await getCart(cartId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!cartId || !cart) {
|
||||||
|
cart = await createCart();
|
||||||
|
cartId = cart.id;
|
||||||
|
cookies().set('cartId', cartId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!variantId) {
|
||||||
|
return 'Missing product variant ID';
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await addToCart(cartId, [{ merchandiseId: variantId, quantity }]);
|
||||||
|
} catch (e) {
|
||||||
|
return quantity === 1 ? 'Error adding item to cart' : 'Error adding items to cart';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const removeItem = async (lineId: string): Promise<String | undefined> => {
|
export const removeItem = async (lineId: string): Promise<String | undefined> => {
|
||||||
const cartId = cookies().get('cartId')?.value;
|
const cartId = cookies().get('cartId')?.value;
|
||||||
|
|
||||||
|
117
components/cart/add-many-to-cart.tsx
Normal file
117
components/cart/add-many-to-cart.tsx
Normal file
@ -0,0 +1,117 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { ChevronDownIcon, ChevronUpIcon } from '@heroicons/react/24/outline';
|
||||||
|
import clsx from 'clsx';
|
||||||
|
import LoadingDots from 'components/loading-dots';
|
||||||
|
import { Product, ProductVariant } from 'lib/shopify/types';
|
||||||
|
import { useTranslations } from 'next-intl';
|
||||||
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
|
import { useState, useTransition } from 'react';
|
||||||
|
import { addItems } from './actions';
|
||||||
|
|
||||||
|
export function AddManyToCart({
|
||||||
|
product,
|
||||||
|
quantity = 1,
|
||||||
|
variants,
|
||||||
|
availableForSale
|
||||||
|
}: {
|
||||||
|
product: Product;
|
||||||
|
quantity: number;
|
||||||
|
variants: ProductVariant[];
|
||||||
|
availableForSale: boolean;
|
||||||
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const t = useTranslations('Index');
|
||||||
|
|
||||||
|
const [currentQuantity, setCurrentQuantity] = useState<number>(quantity);
|
||||||
|
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
const defaultVariantId = variants.length === 1 ? variants[0]?.id : undefined;
|
||||||
|
const variant = variants.find((variant: ProductVariant) =>
|
||||||
|
variant.selectedOptions.every(
|
||||||
|
(option) => option.value === searchParams.get(option.name.toLowerCase())
|
||||||
|
)
|
||||||
|
);
|
||||||
|
console.debug({ product, variant, currentQuantity });
|
||||||
|
const selectedVariantId = variant?.id || defaultVariantId;
|
||||||
|
const title = !availableForSale
|
||||||
|
? t('cart.out-of-stock')
|
||||||
|
: !selectedVariantId
|
||||||
|
? t('cart.options')
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col space-y-2">
|
||||||
|
<div className="font-multilingual flex flex-row items-center space-x-2 border border-white/50">
|
||||||
|
<div className="px-3">{t('cart.quantity-label')}</div>
|
||||||
|
<input
|
||||||
|
value={currentQuantity}
|
||||||
|
onChange={(e) => setCurrentQuantity(Number(e.target.value))}
|
||||||
|
className={clsx(
|
||||||
|
'w-auto grow bg-transparent px-2 py-3 text-right text-white',
|
||||||
|
'outline-none focus:border-0 focus:outline-none focus:ring-0',
|
||||||
|
'focus-visible:ring-none focus-visible:border-none focus-visible:outline-none',
|
||||||
|
'focus-visible:ring-0 focus-visible:ring-offset-0',
|
||||||
|
'active:border-none active:outline-none active:ring-0'
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div className="flex h-full flex-col space-y-px">
|
||||||
|
<button
|
||||||
|
onClick={() => setCurrentQuantity(currentQuantity ? currentQuantity + 1 : 1)}
|
||||||
|
className="grow px-2 py-0.5"
|
||||||
|
>
|
||||||
|
<span>
|
||||||
|
<ChevronUpIcon className="h-4 w-4" />
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setCurrentQuantity(currentQuantity > 0 ? currentQuantity - 1 : 0)}
|
||||||
|
className="grow px-2 py-0.5"
|
||||||
|
>
|
||||||
|
<span>
|
||||||
|
<ChevronDownIcon className="h-4 w-4" />
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
aria-label="Add items to cart"
|
||||||
|
disabled={isPending || !availableForSale || !selectedVariantId}
|
||||||
|
title={title}
|
||||||
|
onClick={() => {
|
||||||
|
// Safeguard in case someone messes with `disabled` in devtools.
|
||||||
|
if (!availableForSale || !selectedVariantId) return;
|
||||||
|
|
||||||
|
startTransition(async () => {
|
||||||
|
const error = await addItems({
|
||||||
|
variantId: selectedVariantId,
|
||||||
|
quantity: currentQuantity
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
// Trigger the error boundary in the root error.js
|
||||||
|
throw new Error(error.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
router.refresh();
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
className={clsx(
|
||||||
|
'relative flex w-full items-center justify-center bg-white p-4 font-serif text-xl tracking-wide text-black hover:opacity-90',
|
||||||
|
{
|
||||||
|
'cursor-not-allowed opacity-60 hover:opacity-60':
|
||||||
|
!availableForSale || !selectedVariantId,
|
||||||
|
'cursor-not-allowed': isPending
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{!isPending ? (
|
||||||
|
<span>{availableForSale ? t('cart.add') : t('cart.out-of-stock')}</span>
|
||||||
|
) : (
|
||||||
|
<LoadingDots className="my-3 bg-black" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
@ -76,25 +76,27 @@
|
|||||||
"cart": {
|
"cart": {
|
||||||
"add": "add to cart",
|
"add": "add to cart",
|
||||||
"out-of-stock": "out of stock",
|
"out-of-stock": "out of stock",
|
||||||
"title": "Shopping Bag",
|
"options": "please select options",
|
||||||
"subtitle": "Review your Order",
|
"quantity-label": "quantity",
|
||||||
"empty": "Your shopping bag is empty",
|
"title": "shopping bag",
|
||||||
"declinedCard": "We couldn't process the purchase. Please check your card information and try again.",
|
"subtitle": "review your order",
|
||||||
"thankYou": "Thank you for your order.",
|
"empty": "your shopping bag is empty",
|
||||||
"subtotal": "Subtotal",
|
"declinedCard": "we couldn't process the purchase. Please check your card information and try again.",
|
||||||
"taxes": "Taxes",
|
"thankYou": "thank you for your order.",
|
||||||
"taxCalculation": "Calculated at checkout",
|
"subtotal": "subtotal",
|
||||||
"shipping": "Shipping",
|
"taxes": "taxes",
|
||||||
"shippingCalculation": "Calculated at checkout",
|
"taxCalculation": "calculated at checkout",
|
||||||
"total": "Total",
|
"shipping": "shipping",
|
||||||
"proceed": "Proceed to Checkout",
|
"shippingCalculation": "calculated at checkout",
|
||||||
"continue": "Continue Shopping",
|
"total": "total",
|
||||||
"note": "Notes",
|
"proceed": "proceed to Checkout",
|
||||||
"notePlaceholder": "Enter any notes you would like to include with your order",
|
"continue": "continue Shopping",
|
||||||
"addNote": "Add a note to your order",
|
"note": "notes",
|
||||||
"editNote": "Edit note",
|
"notePlaceholder": "enter any notes you would like to include with your order",
|
||||||
"hideNote": "Hide",
|
"addNote": "add a note to your order",
|
||||||
"saving": "Saving...",
|
"editNote": "edit note",
|
||||||
|
"hideNote": "hide",
|
||||||
|
"saving": "saving...",
|
||||||
"addFeaturedProduct": "+ add"
|
"addFeaturedProduct": "+ add"
|
||||||
},
|
},
|
||||||
"age-gate": {
|
"age-gate": {
|
||||||
|
@ -76,6 +76,8 @@
|
|||||||
"cart": {
|
"cart": {
|
||||||
"add": "カートに入れる",
|
"add": "カートに入れる",
|
||||||
"out-of-stock": "品切れ中",
|
"out-of-stock": "品切れ中",
|
||||||
|
"options": "オプション",
|
||||||
|
"quantity-label": "購入数",
|
||||||
"title": "ショッピングカード",
|
"title": "ショッピングカード",
|
||||||
"subtitle": "ご注文内容の確認",
|
"subtitle": "ご注文内容の確認",
|
||||||
"empty": "買い物袋が空っぽ",
|
"empty": "買い物袋が空っぽ",
|
||||||
|
Loading…
x
Reference in New Issue
Block a user