From bf093fe8199350f2d20a519af7880d2c80a052a7 Mon Sep 17 00:00:00 2001 From: w3bdesign <45217974+w3bdesign@users.noreply.github.com> Date: Wed, 23 Oct 2024 05:34:32 +0200 Subject: [PATCH] . --- .../Product/AddToCart.component.tsx | 46 +++++++++---------- src/stores/CartProvider.tsx | 25 ++++++---- 2 files changed, 38 insertions(+), 33 deletions(-) diff --git a/src/components/Product/AddToCart.component.tsx b/src/components/Product/AddToCart.component.tsx index f2fa39c1b..6875e2022 100644 --- a/src/components/Product/AddToCart.component.tsx +++ b/src/components/Product/AddToCart.component.tsx @@ -96,7 +96,7 @@ const AddToCart = ({ variationId, fullWidth = false, }: IProductRootObject) => { - const { setCart } = useContext(CartContext); + const { updateCart } = useContext(CartContext); const [requestError, setRequestError] = useState(false); const productId = product?.databaseId ? product?.databaseId : variationId; @@ -107,20 +107,14 @@ const AddToCart = ({ }; // Get cart data query - const { data, refetch } = useQuery(GET_CART, { + const { refetch } = useQuery(GET_CART, { notifyOnNetworkStatusChange: true, - onCompleted: () => { - // Update cart in the localStorage. + onCompleted: (data) => { + // Update cart in the localStorage and React Context. const updatedCart = getFormattedCart(data); - - if (!updatedCart) { - return; + if (updatedCart) { + updateCart(updatedCart); } - - localStorage.setItem('woocommerce-cart', JSON.stringify(updatedCart)); - - // Update cart data in React Context. - setCart(updatedCart); }, }); @@ -129,29 +123,33 @@ const AddToCart = ({ variables: { input: productQueryInput, }, - - onCompleted: () => { - // Update the cart with new values in React context. - refetch(); + onCompleted: (data) => { + // Immediately update the cart with new values + const updatedCart = getFormattedCart(data); + if (updatedCart) { + updateCart(updatedCart); + } }, - onError: () => { setRequestError(true); }, }); - const handleAddToCart = () => { - addToCart(); - // Refetch cart after 2 seconds - setTimeout(() => { - refetch(); - }, 2000); + const handleAddToCart = async () => { + try { + await addToCart(); + // Refetch cart immediately after adding to cart + await refetch(); + } catch (error) { + console.error('Error adding to cart:', error); + setRequestError(true); + } }; return ( <>