๐งช 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 โ
Description
Common usage patterns for the useCart hook, including Add to Cart buttons, mini carts, and more.