Skip to content

Commit dd7449f

Browse files
committed
Make deleting optimistic too.
1 parent cea56f6 commit dd7449f

File tree

2 files changed

+22
-34
lines changed

2 files changed

+22
-34
lines changed

components/cart/delete-item-button.tsx

Lines changed: 21 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,35 @@
11
'use client';
22

33
import { XMarkIcon } from '@heroicons/react/24/outline';
4-
import clsx from 'clsx';
54
import { removeItem } from 'components/cart/actions';
6-
import LoadingDots from 'components/loading-dots';
75
import type { CartItem } from 'lib/shopify/types';
8-
import { useFormState, useFormStatus } from 'react-dom';
6+
import { useFormState } from 'react-dom';
97

10-
function SubmitButton() {
11-
const { pending } = useFormStatus();
12-
13-
return (
14-
<button
15-
type="submit"
16-
onClick={(e: React.FormEvent<HTMLButtonElement>) => {
17-
if (pending) e.preventDefault();
18-
}}
19-
aria-label="Remove cart item"
20-
aria-disabled={pending}
21-
className={clsx(
22-
'ease flex h-[17px] w-[17px] items-center justify-center rounded-full bg-neutral-500 transition-all duration-200',
23-
{
24-
'cursor-not-allowed px-0': pending
25-
}
26-
)}
27-
>
28-
{pending ? (
29-
<LoadingDots className="bg-white" />
30-
) : (
31-
<XMarkIcon className="hover:text-accent-3 mx-[1px] h-4 w-4 text-white dark:text-black" />
32-
)}
33-
</button>
34-
);
35-
}
36-
37-
export function DeleteItemButton({ item }: { item: CartItem }) {
8+
export function DeleteItemButton({
9+
item,
10+
optimisticUpdate
11+
}: {
12+
item: CartItem;
13+
optimisticUpdate: any;
14+
}) {
3815
const [message, formAction] = useFormState(removeItem, null);
3916
const itemId = item.id;
4017
const actionWithVariant = formAction.bind(null, itemId);
4118

4219
return (
43-
<form action={actionWithVariant}>
44-
<SubmitButton />
20+
<form
21+
action={async () => {
22+
optimisticUpdate({ itemId, newQuantity: 0, type: 'minus' });
23+
await actionWithVariant();
24+
}}
25+
>
26+
<button
27+
type="submit"
28+
aria-label="Remove cart item"
29+
className="ease flex h-[17px] w-[17px] items-center justify-center rounded-full bg-neutral-500 transition-all duration-200"
30+
>
31+
<XMarkIcon className="hover:text-accent-3 mx-[1px] h-4 w-4 text-white dark:text-black" />
32+
</button>
4533
<p aria-live="polite" className="sr-only" role="status">
4634
{message}
4735
</p>

components/cart/modal.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ export default function CartModal({ cart: initialCart }: { cart: Cart | undefine
179179
>
180180
<div className="relative flex w-full flex-row justify-between px-1 py-4">
181181
<div className="absolute z-40 -mt-2 ml-[55px]">
182-
<DeleteItemButton item={item} />
182+
<DeleteItemButton item={item} optimisticUpdate={updateCartItem} />
183183
</div>
184184
<Link
185185
href={merchandiseUrl}

0 commit comments

Comments
 (0)