Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
w3bdesign committed Oct 23, 2024
1 parent fa5906c commit bf093fe
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 33 deletions.
46 changes: 22 additions & 24 deletions src/components/Product/AddToCart.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ const AddToCart = ({
variationId,
fullWidth = false,
}: IProductRootObject) => {
const { setCart } = useContext(CartContext);
const { updateCart } = useContext(CartContext);
const [requestError, setRequestError] = useState<boolean>(false);

const productId = product?.databaseId ? product?.databaseId : variationId;
Expand All @@ -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);
},
});

Expand All @@ -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 (
<>
<Button
handleButtonClick={() => handleAddToCart()}
handleButtonClick={handleAddToCart}
buttonDisabled={addToCartLoading || requestError}
fullWidth={fullWidth}
>
Expand Down
25 changes: 16 additions & 9 deletions src/stores/CartProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,37 +49,44 @@ export type TRootObjectNull = RootObject | null | undefined;
interface ICartContext {
cart: RootObject | null | undefined;
setCart: React.Dispatch<React.SetStateAction<TRootObjectNull>>;
updateCart: (newCart: RootObject) => void;
}

const CartState = {
cart: null,
setCart: () => {},
updateCart: () => {},
};

export const CartContext = createContext<ICartContext>(CartState);

/**
* Provides a global application context for the entire application with the cart contents
*/
export const CartProvider = ({ children }: ICartProviderProps) => {
const [cart, setCart] = useState<RootObject | null>();

useEffect(() => {
// Check if we are client-side before we access the localStorage
if (!process.browser) {
return;
}
const localCartData = localStorage.getItem('woocommerce-cart');
if (typeof window !== 'undefined') {
const localCartData = localStorage.getItem('woocommerce-cart');

if (localCartData) {
const cartData: RootObject = JSON.parse(localCartData);
setCart(cartData);
if (localCartData) {
const cartData: RootObject = JSON.parse(localCartData);
setCart(cartData);
}
}
}, []);

const updateCart = (newCart: RootObject) => {
setCart(newCart);
if (typeof window !== 'undefined') {
localStorage.setItem('woocommerce-cart', JSON.stringify(newCart));
}
};

return (
<CartContext.Provider value={{ cart, setCart }}>
<CartContext.Provider value={{ cart, setCart, updateCart }}>
{children}
</CartContext.Provider>
);
Expand Down

0 comments on commit bf093fe

Please sign in to comment.