add multiple items to cart at once

This commit is contained in:
Sol Irvine 2023-08-24 09:59:14 -07:00
parent 37a5e61ca0
commit 4ea96cc6e5
5 changed files with 175 additions and 21 deletions

View File

@ -3,7 +3,7 @@ import { notFound } from 'next/navigation';
import { Suspense } from 'react';
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 Label from 'components/label';
import { SupportedLocale } from 'components/layout/navbar/language-control';
@ -135,7 +135,9 @@ export default async function ProductPage({
<div className="max-w-sm">
<VariantSelector options={product.options} variants={product.variants} />
<AddToCart
<AddManyToCart
product={product}
quantity={1}
variants={product.variants}
availableForSale={product.availableForSale}
/>

View File

@ -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> => {
const cartId = cookies().get('cartId')?.value;

View 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>
);
}

View File

@ -76,25 +76,27 @@
"cart": {
"add": "add to cart",
"out-of-stock": "out of stock",
"title": "Shopping Bag",
"subtitle": "Review your Order",
"empty": "Your shopping bag is empty",
"declinedCard": "We couldn't process the purchase. Please check your card information and try again.",
"thankYou": "Thank you for your order.",
"subtotal": "Subtotal",
"taxes": "Taxes",
"taxCalculation": "Calculated at checkout",
"shipping": "Shipping",
"shippingCalculation": "Calculated at checkout",
"total": "Total",
"proceed": "Proceed to Checkout",
"continue": "Continue Shopping",
"note": "Notes",
"notePlaceholder": "Enter any notes you would like to include with your order",
"addNote": "Add a note to your order",
"editNote": "Edit note",
"hideNote": "Hide",
"saving": "Saving...",
"options": "please select options",
"quantity-label": "quantity",
"title": "shopping bag",
"subtitle": "review your order",
"empty": "your shopping bag is empty",
"declinedCard": "we couldn't process the purchase. Please check your card information and try again.",
"thankYou": "thank you for your order.",
"subtotal": "subtotal",
"taxes": "taxes",
"taxCalculation": "calculated at checkout",
"shipping": "shipping",
"shippingCalculation": "calculated at checkout",
"total": "total",
"proceed": "proceed to Checkout",
"continue": "continue Shopping",
"note": "notes",
"notePlaceholder": "enter any notes you would like to include with your order",
"addNote": "add a note to your order",
"editNote": "edit note",
"hideNote": "hide",
"saving": "saving...",
"addFeaturedProduct": "+ add"
},
"age-gate": {

View File

@ -76,6 +76,8 @@
"cart": {
"add": "カートに入れる",
"out-of-stock": "品切れ中",
"options": "オプション",
"quantity-label": "購入数",
"title": "ショッピングカード",
"subtitle": "ご注文内容の確認",
"empty": "買い物袋が空っぽ",