Skip to content

Commit

Permalink
Make deleting optimistic too.
Browse files Browse the repository at this point in the history
  • Loading branch information
leerob committed Jul 25, 2024
1 parent cea56f6 commit dd7449f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 34 deletions.
54 changes: 21 additions & 33 deletions components/cart/delete-item-button.tsx
Original file line number Diff line number Diff line change
@@ -1,47 +1,35 @@
'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 { useFormState, useFormStatus } from 'react-dom';
import { useFormState } from 'react-dom';

function SubmitButton() {
const { pending } = useFormStatus();

return (
<button
type="submit"
onClick={(e: React.FormEvent<HTMLButtonElement>) => {
if (pending) e.preventDefault();
}}
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': pending
}
)}
>
{pending ? (
<LoadingDots className="bg-white" />
) : (
<XMarkIcon className="hover:text-accent-3 mx-[1px] h-4 w-4 text-white dark:text-black" />
)}
</button>
);
}

export function DeleteItemButton({ item }: { item: CartItem }) {
export function DeleteItemButton({
item,
optimisticUpdate
}: {
item: CartItem;
optimisticUpdate: any;
}) {
const [message, formAction] = useFormState(removeItem, null);
const itemId = item.id;
const actionWithVariant = formAction.bind(null, itemId);

return (
<form action={actionWithVariant}>
<SubmitButton />
<form
action={async () => {
optimisticUpdate({ itemId, newQuantity: 0, type: 'minus' });
await actionWithVariant();
}}
>
<button
type="submit"
aria-label="Remove cart item"
className="ease flex h-[17px] w-[17px] items-center justify-center rounded-full bg-neutral-500 transition-all duration-200"
>
<XMarkIcon className="hover:text-accent-3 mx-[1px] h-4 w-4 text-white dark:text-black" />
</button>
<p aria-live="polite" className="sr-only" role="status">
{message}
</p>
Expand Down
2 changes: 1 addition & 1 deletion components/cart/modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ export default function CartModal({ cart: initialCart }: { cart: Cart | undefine
>
<div className="relative flex w-full flex-row justify-between px-1 py-4">
<div className="absolute z-40 -mt-2 ml-[55px]">
<DeleteItemButton item={item} />
<DeleteItemButton item={item} optimisticUpdate={updateCartItem} />
</div>
<Link
href={merchandiseUrl}
Expand Down

0 comments on commit dd7449f

Please sign in to comment.