mirror of
https://github.com/vercel/commerce.git
synced 2025-03-14 06:32:32 +00:00
Improves form submissions and updates dependencies (#1209)
This commit is contained in:
parent
ece49c4265
commit
1f47796529
@ -1,9 +1,11 @@
|
||||
'use server';
|
||||
|
||||
import { TAGS } from 'lib/constants';
|
||||
import { addToCart, createCart, getCart, removeFromCart, updateCart } from 'lib/shopify';
|
||||
import { revalidateTag } from 'next/cache';
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
export const addItem = async (variantId: string | undefined): Promise<String | undefined> => {
|
||||
export async function addItem(prevState: any, selectedVariantId: string | undefined) {
|
||||
let cartId = cookies().get('cartId')?.value;
|
||||
let cart;
|
||||
|
||||
@ -17,45 +19,56 @@ export const addItem = async (variantId: string | undefined): Promise<String | u
|
||||
cookies().set('cartId', cartId);
|
||||
}
|
||||
|
||||
if (!variantId) {
|
||||
if (!selectedVariantId) {
|
||||
return 'Missing product variant ID';
|
||||
}
|
||||
|
||||
try {
|
||||
await addToCart(cartId, [{ merchandiseId: variantId, quantity: 1 }]);
|
||||
await addToCart(cartId, [{ merchandiseId: selectedVariantId, quantity: 1 }]);
|
||||
revalidateTag(TAGS.cart);
|
||||
} catch (e) {
|
||||
return 'Error adding item to cart';
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const removeItem = async (lineId: string): Promise<String | undefined> => {
|
||||
export async function removeItem(prevState: any, lineId: string) {
|
||||
const cartId = cookies().get('cartId')?.value;
|
||||
|
||||
if (!cartId) {
|
||||
return 'Missing cart ID';
|
||||
}
|
||||
|
||||
try {
|
||||
await removeFromCart(cartId, [lineId]);
|
||||
revalidateTag(TAGS.cart);
|
||||
} catch (e) {
|
||||
return 'Error removing item from cart';
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const updateItemQuantity = async ({
|
||||
lineId,
|
||||
variantId,
|
||||
quantity
|
||||
}: {
|
||||
lineId: string;
|
||||
variantId: string;
|
||||
quantity: number;
|
||||
}): Promise<String | undefined> => {
|
||||
export async function updateItemQuantity(
|
||||
prevState: any,
|
||||
payload: {
|
||||
lineId: string;
|
||||
variantId: string;
|
||||
quantity: number;
|
||||
}
|
||||
) {
|
||||
const cartId = cookies().get('cartId')?.value;
|
||||
|
||||
if (!cartId) {
|
||||
return 'Missing cart ID';
|
||||
}
|
||||
|
||||
const { lineId, variantId, quantity } = payload;
|
||||
|
||||
try {
|
||||
if (quantity === 0) {
|
||||
await removeFromCart(cartId, [lineId]);
|
||||
revalidateTag(TAGS.cart);
|
||||
return;
|
||||
}
|
||||
|
||||
await updateCart(cartId, [
|
||||
{
|
||||
id: lineId,
|
||||
@ -63,7 +76,8 @@ export const updateItemQuantity = async ({
|
||||
quantity
|
||||
}
|
||||
]);
|
||||
revalidateTag(TAGS.cart);
|
||||
} catch (e) {
|
||||
return 'Error updating item quantity';
|
||||
}
|
||||
};
|
||||
}
|
||||
|
@ -5,8 +5,67 @@ import clsx from 'clsx';
|
||||
import { addItem } from 'components/cart/actions';
|
||||
import LoadingDots from 'components/loading-dots';
|
||||
import { ProductVariant } from 'lib/shopify/types';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useTransition } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import {
|
||||
// @ts-ignore
|
||||
experimental_useFormState as useFormState,
|
||||
experimental_useFormStatus as useFormStatus
|
||||
} from 'react-dom';
|
||||
|
||||
function SubmitButton({
|
||||
availableForSale,
|
||||
selectedVariantId
|
||||
}: {
|
||||
availableForSale: boolean;
|
||||
selectedVariantId: string | undefined;
|
||||
}) {
|
||||
const { pending } = useFormStatus();
|
||||
const buttonClasses =
|
||||
'relative flex w-full items-center justify-center rounded-full bg-blue-600 p-4 tracking-wide text-white';
|
||||
const disabledClasses = 'cursor-not-allowed opacity-60 hover:opacity-60';
|
||||
|
||||
if (!availableForSale) {
|
||||
return (
|
||||
<button aria-disabled className={clsx(buttonClasses, disabledClasses)}>
|
||||
Out Of Stock
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
if (!selectedVariantId) {
|
||||
return (
|
||||
<button
|
||||
aria-label="Please select an option"
|
||||
aria-disabled
|
||||
className={clsx(buttonClasses, disabledClasses)}
|
||||
>
|
||||
<div className="absolute left-0 ml-4">
|
||||
<PlusIcon className="h-5" />
|
||||
</div>
|
||||
Add To Cart
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={(e: React.FormEvent<HTMLButtonElement>) => {
|
||||
if (pending) e.preventDefault();
|
||||
}}
|
||||
aria-label="Add to cart"
|
||||
aria-disabled={pending}
|
||||
className={clsx(buttonClasses, {
|
||||
'hover:opacity-90': true,
|
||||
disabledClasses: pending
|
||||
})}
|
||||
>
|
||||
<div className="absolute left-0 ml-4">
|
||||
{pending ? <LoadingDots className="mb-3 bg-white" /> : <PlusIcon className="h-5" />}
|
||||
</div>
|
||||
Add To Cart
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function AddToCart({
|
||||
variants,
|
||||
@ -15,9 +74,8 @@ export function AddToCart({
|
||||
variants: ProductVariant[];
|
||||
availableForSale: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [message, formAction] = useFormState(addItem, null);
|
||||
const searchParams = useSearchParams();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const defaultVariantId = variants.length === 1 ? variants[0]?.id : undefined;
|
||||
const variant = variants.find((variant: ProductVariant) =>
|
||||
variant.selectedOptions.every(
|
||||
@ -25,44 +83,14 @@ export function AddToCart({
|
||||
)
|
||||
);
|
||||
const selectedVariantId = variant?.id || defaultVariantId;
|
||||
const title = !availableForSale
|
||||
? 'Out of stock'
|
||||
: !selectedVariantId
|
||||
? 'Please select options'
|
||||
: undefined;
|
||||
const actionWithVariant = formAction.bind(null, selectedVariantId);
|
||||
|
||||
return (
|
||||
<button
|
||||
aria-label="Add item 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 addItem(selectedVariantId);
|
||||
|
||||
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 rounded-full bg-blue-600 p-4 tracking-wide text-white hover:opacity-90',
|
||||
{
|
||||
'cursor-not-allowed opacity-60 hover:opacity-60': !availableForSale || !selectedVariantId,
|
||||
'cursor-not-allowed': isPending
|
||||
}
|
||||
)}
|
||||
>
|
||||
<div className="absolute left-0 ml-4">
|
||||
{!isPending ? <PlusIcon className="h-5" /> : <LoadingDots className="mb-3 bg-white" />}
|
||||
</div>
|
||||
<span>{availableForSale ? 'Add To Cart' : 'Out Of Stock'}</span>
|
||||
</button>
|
||||
<form action={actionWithVariant}>
|
||||
<SubmitButton availableForSale={availableForSale} selectedVariantId={selectedVariantId} />
|
||||
<p aria-live="polite" className="sr-only" role="status">
|
||||
{message}
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
@ -1,40 +1,35 @@
|
||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import LoadingDots from 'components/loading-dots';
|
||||
import { useRouter } from 'next/navigation';
|
||||
'use client';
|
||||
|
||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import clsx from 'clsx';
|
||||
import { removeItem } from 'components/cart/actions';
|
||||
import LoadingDots from 'components/loading-dots';
|
||||
import type { CartItem } from 'lib/shopify/types';
|
||||
import { useTransition } from 'react';
|
||||
import {
|
||||
// @ts-ignore
|
||||
experimental_useFormState as useFormState,
|
||||
experimental_useFormStatus as useFormStatus
|
||||
} from 'react-dom';
|
||||
|
||||
export default function DeleteItemButton({ item }: { item: CartItem }) {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
function SubmitButton() {
|
||||
const { pending } = useFormStatus();
|
||||
|
||||
return (
|
||||
<button
|
||||
aria-label="Remove cart item"
|
||||
onClick={() => {
|
||||
startTransition(async () => {
|
||||
const error = await removeItem(item.id);
|
||||
|
||||
if (error) {
|
||||
// Trigger the error boundary in the root error.js
|
||||
throw new Error(error.toString());
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
});
|
||||
type="submit"
|
||||
onClick={(e: React.FormEvent<HTMLButtonElement>) => {
|
||||
if (pending) e.preventDefault();
|
||||
}}
|
||||
disabled={isPending}
|
||||
aria-label="Remove cart item"
|
||||
aria-disabled={pending}
|
||||
className={clsx(
|
||||
'ease flex h-[17px] w-[17px] items-center justify-center rounded-full bg-neutral-500 transition-all duration-200',
|
||||
{
|
||||
'cursor-not-allowed px-0': isPending
|
||||
'cursor-not-allowed px-0': pending
|
||||
}
|
||||
)}
|
||||
>
|
||||
{isPending ? (
|
||||
{pending ? (
|
||||
<LoadingDots className="bg-white" />
|
||||
) : (
|
||||
<XMarkIcon className="hover:text-accent-3 mx-[1px] h-4 w-4 text-white dark:text-black" />
|
||||
@ -42,3 +37,18 @@ export default function DeleteItemButton({ item }: { item: CartItem }) {
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function DeleteItemButton({ item }: { item: CartItem }) {
|
||||
const [message, formAction] = useFormState(removeItem, null);
|
||||
const itemId = item.id;
|
||||
const actionWithVariant = formAction.bind(null, itemId);
|
||||
|
||||
return (
|
||||
<form action={actionWithVariant}>
|
||||
<SubmitButton />
|
||||
<p aria-live="polite" className="sr-only" role="status">
|
||||
{message}
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
@ -1,54 +1,36 @@
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useTransition } from 'react';
|
||||
'use client';
|
||||
|
||||
import { MinusIcon, PlusIcon } from '@heroicons/react/24/outline';
|
||||
import clsx from 'clsx';
|
||||
import { removeItem, updateItemQuantity } from 'components/cart/actions';
|
||||
import { updateItemQuantity } from 'components/cart/actions';
|
||||
import LoadingDots from 'components/loading-dots';
|
||||
import type { CartItem } from 'lib/shopify/types';
|
||||
import {
|
||||
// @ts-ignore
|
||||
experimental_useFormState as useFormState,
|
||||
experimental_useFormStatus as useFormStatus
|
||||
} from 'react-dom';
|
||||
|
||||
export default function EditItemQuantityButton({
|
||||
item,
|
||||
type
|
||||
}: {
|
||||
item: CartItem;
|
||||
type: 'plus' | 'minus';
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
function SubmitButton({ type }: { type: 'plus' | 'minus' }) {
|
||||
const { pending } = useFormStatus();
|
||||
|
||||
return (
|
||||
<button
|
||||
aria-label={type === 'plus' ? 'Increase item quantity' : 'Reduce item quantity'}
|
||||
onClick={() => {
|
||||
startTransition(async () => {
|
||||
const error =
|
||||
type === 'minus' && item.quantity - 1 === 0
|
||||
? await removeItem(item.id)
|
||||
: await updateItemQuantity({
|
||||
lineId: item.id,
|
||||
variantId: item.merchandise.id,
|
||||
quantity: type === 'plus' ? item.quantity + 1 : item.quantity - 1
|
||||
});
|
||||
|
||||
if (error) {
|
||||
// Trigger the error boundary in the root error.js
|
||||
throw new Error(error.toString());
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
});
|
||||
type="submit"
|
||||
onClick={(e: React.FormEvent<HTMLButtonElement>) => {
|
||||
if (pending) e.preventDefault();
|
||||
}}
|
||||
disabled={isPending}
|
||||
aria-label={type === 'plus' ? 'Increase item quantity' : 'Reduce item quantity'}
|
||||
aria-disabled={pending}
|
||||
className={clsx(
|
||||
'ease flex h-full min-w-[36px] max-w-[36px] flex-none items-center justify-center rounded-full px-2 transition-all duration-200 hover:border-neutral-800 hover:opacity-80',
|
||||
{
|
||||
'cursor-not-allowed': isPending,
|
||||
'cursor-not-allowed': pending,
|
||||
'ml-auto': type === 'minus'
|
||||
}
|
||||
)}
|
||||
>
|
||||
{isPending ? (
|
||||
{pending ? (
|
||||
<LoadingDots className="bg-black dark:bg-white" />
|
||||
) : type === 'plus' ? (
|
||||
<PlusIcon className="h-4 w-4 dark:text-neutral-500" />
|
||||
@ -58,3 +40,22 @@ export default function EditItemQuantityButton({
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function EditItemQuantityButton({ item, type }: { item: CartItem; type: 'plus' | 'minus' }) {
|
||||
const [message, formAction] = useFormState(updateItemQuantity, null);
|
||||
const payload = {
|
||||
lineId: item.id,
|
||||
variantId: item.merchandise.id,
|
||||
quantity: type === 'plus' ? item.quantity + 1 : item.quantity - 1
|
||||
};
|
||||
const actionWithVariant = formAction.bind(null, payload);
|
||||
|
||||
return (
|
||||
<form action={actionWithVariant}>
|
||||
<SubmitButton type={type} />
|
||||
<p aria-live="polite" className="sr-only" role="status">
|
||||
{message}
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
@ -10,8 +10,8 @@ import Image from 'next/image';
|
||||
import Link from 'next/link';
|
||||
import { Fragment, useEffect, useRef, useState } from 'react';
|
||||
import CloseCart from './close-cart';
|
||||
import DeleteItemButton from './delete-item-button';
|
||||
import EditItemQuantityButton from './edit-item-quantity-button';
|
||||
import { DeleteItemButton } from './delete-item-button';
|
||||
import { EditItemQuantityButton } from './edit-item-quantity-button';
|
||||
import OpenCart from './open-cart';
|
||||
|
||||
type MerchandiseSearchParams = {
|
||||
|
@ -58,9 +58,8 @@ export default async function Footer() {
|
||||
<hr className="mx-4 hidden h-4 w-[1px] border-l border-neutral-400 md:inline-block" />
|
||||
<p>Designed in California</p>
|
||||
<p className="md:ml-auto">
|
||||
Crafted by{' '}
|
||||
<a href="https://vercel.com" className="text-black dark:text-white">
|
||||
▲ Vercel
|
||||
Crafted by ▲ Vercel
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
|
@ -27,6 +27,7 @@ export default function Search() {
|
||||
return (
|
||||
<form onSubmit={onSubmit} className="w-max-[550px] relative w-full lg:w-80 xl:w-full">
|
||||
<input
|
||||
key={searchParams?.get('q')}
|
||||
type="text"
|
||||
name="search"
|
||||
placeholder="Search for products..."
|
||||
|
@ -19,7 +19,11 @@ export default function FilterList({ list, title }: { list: ListItem[]; title?:
|
||||
return (
|
||||
<>
|
||||
<nav>
|
||||
{title ? <h3 className="hidden text-xs text-neutral-500 md:block">{title}</h3> : null}
|
||||
{title ? (
|
||||
<h3 className="hidden text-xs text-neutral-500 dark:text-neutral-400 md:block">
|
||||
{title}
|
||||
</h3>
|
||||
) : null}
|
||||
<ul className="hidden md:block">
|
||||
<FilterItemList list={list} />
|
||||
</ul>
|
||||
|
@ -22,7 +22,8 @@ export const sorting: SortFilterItem[] = [
|
||||
|
||||
export const TAGS = {
|
||||
collections: 'collections',
|
||||
products: 'products'
|
||||
products: 'products',
|
||||
cart: 'cart'
|
||||
};
|
||||
|
||||
export const HIDDEN_PRODUCT_TAG = 'nextjs-frontend-hidden';
|
||||
|
@ -258,6 +258,7 @@ export async function getCart(cartId: string): Promise<Cart | undefined> {
|
||||
const res = await shopifyFetch<ShopifyCartOperation>({
|
||||
query: getCartQuery,
|
||||
variables: { cartId },
|
||||
tags: [TAGS.cart],
|
||||
cache: 'no-store'
|
||||
});
|
||||
|
||||
|
32
package.json
32
package.json
@ -22,30 +22,30 @@
|
||||
"*": "prettier --write --ignore-unknown"
|
||||
},
|
||||
"dependencies": {
|
||||
"@headlessui/react": "^1.7.15",
|
||||
"@headlessui/react": "^1.7.17",
|
||||
"@heroicons/react": "^2.0.18",
|
||||
"clsx": "^2.0.0",
|
||||
"next": "13.4.13-canary.15",
|
||||
"next": "13.5.4",
|
||||
"react": "18.2.0",
|
||||
"react-dom": "18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/container-queries": "^0.1.1",
|
||||
"@tailwindcss/typography": "^0.5.9",
|
||||
"@types/node": "20.4.4",
|
||||
"@types/react": "18.2.16",
|
||||
"@types/react-dom": "18.2.7",
|
||||
"@tailwindcss/typography": "^0.5.10",
|
||||
"@types/node": "20.8.4",
|
||||
"@types/react": "18.2.10",
|
||||
"@types/react-dom": "18.2.10",
|
||||
"@vercel/git-hooks": "^1.0.0",
|
||||
"autoprefixer": "^10.4.14",
|
||||
"eslint": "^8.45.0",
|
||||
"eslint-config-next": "^13.4.12",
|
||||
"eslint-config-prettier": "^8.8.0",
|
||||
"eslint-plugin-unicorn": "^48.0.0",
|
||||
"lint-staged": "^13.2.3",
|
||||
"postcss": "^8.4.27",
|
||||
"prettier": "3.0.1",
|
||||
"prettier-plugin-tailwindcss": "^0.4.1",
|
||||
"autoprefixer": "^10.4.16",
|
||||
"eslint": "^8.51.0",
|
||||
"eslint-config-next": "^13.5.4",
|
||||
"eslint-config-prettier": "^9.0.0",
|
||||
"eslint-plugin-unicorn": "^48.0.1",
|
||||
"lint-staged": "^14.0.1",
|
||||
"postcss": "^8.4.31",
|
||||
"prettier": "3.0.3",
|
||||
"prettier-plugin-tailwindcss": "^0.5.5",
|
||||
"tailwindcss": "^3.3.3",
|
||||
"typescript": "5.1.6"
|
||||
"typescript": "5.2.2"
|
||||
}
|
||||
}
|
||||
|
1472
pnpm-lock.yaml
generated
1472
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@ -1,10 +1,9 @@
|
||||
/** @type {import('prettier').Config} */
|
||||
module.exports = {
|
||||
singleQuote: true,
|
||||
arrowParens: 'always',
|
||||
trailingComma: 'none',
|
||||
printWidth: 100,
|
||||
tabWidth: 2,
|
||||
// pnpm doesn't support plugin autoloading
|
||||
// https://github.com/tailwindlabs/prettier-plugin-tailwindcss#installation
|
||||
plugins: [require('prettier-plugin-tailwindcss')]
|
||||
plugins: ['prettier-plugin-tailwindcss']
|
||||
};
|
||||
|
Loading…
x
Reference in New Issue
Block a user