Skip to main content

๐Ÿงช Cart Usage Examples

Once your app is wrapped in <CartProvider>, you can use the useCart() hook anywhere in the tree to access cart state and actions.


๐Ÿ›’ Add to Cart Buttonโ€‹

"use client";

import { useCart } from "@nextshopkit/sdk/client";

export function AddToCartButton({ merchandiseId }: { merchandiseId: string }) {
const { addProducts, loading } = useCart();

const handleClick = () => {
addProducts([{ merchandiseId, quantity: 1 }]);
};

return (
<button onClick={handleClick} disabled={loading}>
{loading ? "Adding..." : "Add to Cart"}
</button>
);
}

๐Ÿ›๏ธ Mini Cart in Headerโ€‹

"use client";

import { useCart } from "@nextshopkit/sdk/client";

export function MiniCart() {
const { cart, totalCount, totalPrice } = useCart();

return (
<div>
<p>{totalCount} items</p>
<p>Total: โ‚ฌ{totalPrice.toFixed(2)}</p>
<a href="/cart">View Cart</a>
</div>
);
}

๐Ÿ” Update Quantityโ€‹

const { updateQuantity } = useCart();

const update = () => {
updateQuantity("gid://shopify/CartLine/123", 3);
};

โŒ Remove Itemโ€‹

const { removeProduct } = useCart();

const remove = () => {
removeProduct("gid://shopify/CartLine/123");
};

๐ŸŽŸ๏ธ Apply Discountโ€‹

const { applyDiscountCode } = useCart();

const apply = () => {
applyDiscountCode("SUMMER10");
};

๐Ÿ”„ Reset Cartโ€‹

const { resetCart } = useCart();

const reset = () => {
resetCart();
};

๐Ÿงฌ Use Typed Custom Attributesโ€‹

If you configured customAttributes in your CartProviderConfig, you can access them like this:

const { typedCartAttributes } = useCart();

const isB2B = typedCartAttributes?.customIsB2B;

โžก๏ธ See Types Reference โ†’ for details.


โœ… Next: Advanced Usage โ†’