Skip to content

Commit

Permalink
Merge branch 'main' of github.com:tinloof/medusa-b2c-starter
Browse files Browse the repository at this point in the history
  • Loading branch information
haninekkoub committed Oct 23, 2024
2 parents 45c8d5d + f67a465 commit c825870
Show file tree
Hide file tree
Showing 6 changed files with 83 additions and 89 deletions.
22 changes: 1 addition & 21 deletions storefront/actions/medusa/cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export async function updateCartQuantity({
lineItem,
quantity,
}: {
countryCode?: string;
countryCode: string;
lineItem: string;
quantity: number;
}) {
Expand Down Expand Up @@ -141,26 +141,6 @@ export async function updateCartQuantity({
}
}

export async function deleteLineItem({
countryCode = "us",
lineItem,
}: {
countryCode?: string;
lineItem: string;
}) {
const cart = await getOrSetCart(countryCode);

if (!cart) {
throw new Error("Error retrieving or creating cart");
}

const cacheTag = await getCacheTag("carts");

await medusa.store.cart.deleteLineItem(cart.id, lineItem).then(() => {
revalidateTag(cacheTag);
});
}

export async function updateCart(data: StoreUpdateCart) {
const cartId = await getCartId();
if (!cartId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default function OptionsSelect({options}: Props) {
value: value.toLowerCase(),
}));

if (!values || values?.length === 0) return null;
if (!values || values.length <= 1) return null;
const activeOption = selectedOptions[option.title.toLowerCase()];
const setOption = (value: string) =>
setSelectedOptions((prev) => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,14 @@ export default function StickyAtc({
)}
>
<div className="flex items-center justify-center gap-3">
{product.options && (
<div className="w-fit">
<OptionsSelect options={product.options} />
</div>
)}
{product.options &&
product.options.some(
(option) => (option.values?.length || 0) > 1,
) && (
<div className="w-fit">
<OptionsSelect options={product.options} />
</div>
)}
<AddToCart region_id={region_id} variant="sticky" />
</div>
</div>
Expand Down
119 changes: 63 additions & 56 deletions storefront/components/global/header/cart/cart-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {addToCart, updateCartQuantity} from "@/actions/medusa/cart";
import {usePathname} from "next/navigation";
import {
createContext,
useCallback,
useContext,
useEffect,
useOptimistic,
Expand Down Expand Up @@ -43,77 +44,82 @@ const CartContext = createContext<
export function CartProvider({
cart,
children,
countryCode,
}: PropsWithChildren<{
cart: Cart | null;
countryCode: string;
}>) {
const [optimisticCart, setOptimisticCart] = useOptimistic<Cart | null>(cart);
const [cartOpen, setCartOpen] = useState(false);

const [, startTransition] = useTransition();
const pathname = usePathname();

const handleOptimisticAddToCart = async (payload: AddToCartEventPayload) => {
setCartOpen(true);

startTransition(async () => {
setOptimisticCart((prev) => {
const items = [...(prev?.items || [])];

const existingItemIndex = items.findIndex(
({variant}) => variant?.id === payload.productVariant.id,
);

if (existingItemIndex > -1) {
const item = items[existingItemIndex];
items[existingItemIndex] = {
...item,
quantity: item.quantity + 1,
const handleOptimisticAddToCart = useCallback(
async (payload: AddToCartEventPayload) => {
setCartOpen(true);

startTransition(async () => {
setOptimisticCart((prev) => {
const items = [...(prev?.items || [])];

const existingItemIndex = items.findIndex(
({variant}) => variant?.id === payload.productVariant.id,
);

if (existingItemIndex > -1) {
const item = items[existingItemIndex];
items[existingItemIndex] = {
...item,
quantity: item.quantity + 1,
};
return {...prev, items} as Cart;
}

const priceAmount =
payload.productVariant.calculated_price?.calculated_amount || 0;

const newItem: StoreCartLineItem = {
cart: prev || ({} as StoreCart),
cart_id: prev?.id || "",
discount_tax_total: 0,
discount_total: 0,
id: generateOptimisticItemId(payload.productVariant.id),
is_discountable: false,
is_tax_inclusive: false,
item_subtotal: priceAmount,
item_tax_total: 0,
item_total: priceAmount,
original_subtotal: priceAmount,
original_tax_total: 0,
original_total: priceAmount,
product: payload.productVariant.product || undefined,
quantity: 1,
requires_shipping: true,
subtotal: priceAmount,
tax_total: 0,
title: payload.productVariant.title || "",
total: priceAmount,
unit_price: priceAmount,
variant: payload.productVariant || undefined,
};
return {...prev, items} as Cart;
}

const priceAmount =
payload.productVariant.calculated_price?.calculated_amount || 0;

const newItem: StoreCartLineItem = {
cart: prev || ({} as StoreCart),
cart_id: prev?.id || "",
discount_tax_total: 0,
discount_total: 0,
id: generateOptimisticItemId(payload.productVariant.id),
is_discountable: false,
is_tax_inclusive: false,
item_subtotal: priceAmount,
item_tax_total: 0,
item_total: priceAmount,
original_subtotal: priceAmount,
original_tax_total: 0,
original_total: priceAmount,
product: payload.productVariant.product || undefined,
quantity: 1,
requires_shipping: true,
subtotal: priceAmount,
tax_total: 0,
title: payload.productVariant.title || "",
total: priceAmount,
unit_price: priceAmount,
variant: payload.productVariant || undefined,
};

const newItems = [...items, newItem];
const newItems = [...items, newItem];

const newTotal = calculateCartTotal(newItems);
const newTotal = calculateCartTotal(newItems);

return {...prev, items: newItems, total: newTotal} as Cart;
});
return {...prev, items: newItems, total: newTotal} as Cart;
});

await addToCart({
quantity: 1,
region_id: payload.regionId,
variantId: payload.productVariant.id,
await addToCart({
quantity: 1,
region_id: payload.regionId,
variantId: payload.productVariant.id,
});
});
});
};
},
[setCartOpen, setOptimisticCart],
);

useEffect(() => {
addToCartEventBus.registerCartAddHandler(handleOptimisticAddToCart);
Expand Down Expand Up @@ -164,6 +170,7 @@ export function CartProvider({

if (!isOptimisticItemId(lineItem)) {
await updateCartQuantity({
countryCode,
lineItem,
quantity,
});
Expand Down
2 changes: 1 addition & 1 deletion storefront/components/global/header/cart/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export default async function Cart({
) : null;

return (
<CartProvider cart={cart}>
<CartProvider cart={cart} countryCode={countryCode}>
<CartUI addons={addons} />
</CartProvider>
);
Expand Down
14 changes: 9 additions & 5 deletions storefront/components/shared/input-combobox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,19 @@ export default forwardRef<
return (
<div className="relative w-full">
<div className="relative flex w-full items-center">
<Icon
className="absolute left-3 text-accent opacity-60"
name="Search"
/>
{!isDisabled && (
<Icon
className="absolute left-3 text-accent opacity-60"
name="Search"
/>
)}
<input
className={cx(
className,
"w-full rounded-lg border-[1.5px] border-accent bg-transparent py-[11px] pl-10 pr-[16px] font-medium outline-none placeholder:font-medium placeholder:text-accent placeholder:opacity-60",
"w-full rounded-lg border-[1.5px] border-accent bg-transparent py-[11px] pr-[16px] font-medium outline-none placeholder:font-medium placeholder:text-accent placeholder:opacity-60",
{
"pl-[16px]": isDisabled,
"pl-10": !isDisabled,
"size-4 border-2 border-accent bg-transparent p-1 accent-accent outline-none":
type === "checkbox",
},
Expand Down

0 comments on commit c825870

Please sign in to comment.