From 7c845b28a668a3e343e139f123914b767bcbe185 Mon Sep 17 00:00:00 2001 From: Amine Date: Thu, 24 Oct 2024 10:07:34 +0100 Subject: [PATCH] fix cart total --- .../components/global/header/cart/cart-context.tsx | 9 +++++++-- storefront/components/global/header/cart/cart-footer.tsx | 8 ++++---- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/storefront/components/global/header/cart/cart-context.tsx b/storefront/components/global/header/cart/cart-context.tsx index d8ff5e4..dc14665 100644 --- a/storefront/components/global/header/cart/cart-context.tsx +++ b/storefront/components/global/header/cart/cart-context.tsx @@ -61,6 +61,8 @@ export function CartProvider({ startTransition(async () => { setOptimisticCart((prev) => { + console.log({prev: cart?.items?.length}); + const items = [...(prev?.items || [])]; const existingItemIndex = items.findIndex( @@ -108,7 +110,7 @@ export function CartProvider({ const newTotal = calculateCartTotal(newItems); - return {...prev, items: newItems, total: newTotal} as Cart; + return {...prev, item_total: newTotal, items: newItems} as Cart; }); await addToCart({ @@ -211,5 +213,8 @@ export function isOptimisticItemId(id: string) { } function calculateCartTotal(cartItems: StoreCartLineItem[]) { - return cartItems.reduce((acc, item) => acc + item.total, 0) || 0; + return ( + cartItems.reduce((acc, item) => acc + item.unit_price * item.quantity, 0) || + 0 + ); } diff --git a/storefront/components/global/header/cart/cart-footer.tsx b/storefront/components/global/header/cart/cart-footer.tsx index ef6dad8..355e3d1 100644 --- a/storefront/components/global/header/cart/cart-footer.tsx +++ b/storefront/components/global/header/cart/cart-footer.tsx @@ -9,9 +9,9 @@ import {useCart} from "./cart-context"; export default function CartFooter() { const {cart} = useCart(); - const total = cart + const item_total = cart ? convertToLocale({ - amount: cart.total, + amount: cart.item_total, currency_code: cart.currency_code, }) : null; @@ -33,9 +33,9 @@ export default function CartFooter() { Taxes and shipping calculated at checkout - {total && ( + {item_total && ( - {total} + {item_total} )}