useCart hook
Learn how to use the useCart hook to access and modify cart data in Checkout extensions, including adding and removing cart items.
This feature is only available for stores using B2B Buyer Portal, which is currently available to selected accounts.
The useCart hook allows you to access cart data and perform mutations that are reflected across other entities within the Checkout data layer.
Usage
_10import { useCart } from '@vtex/checkout';_10_10const TotalItems = () => {_10 const cart = useCart();_10_10 return <div>Items: {cart.items.length}</div>;_10};
You can also use useCart to interact with the Checkout data layer by mutating the cart items list:
_12import { useCart } from '@vtex/checkout';_12_12const AddItemExample = () => {_12 const cart = useCart();_12 const addItem = () => cart.addItem({_12 quantity: 1,_12 seller: '1',_12 id: '8392'_12 });_12_12 return <button onClick={addItem}>Add to cart</button>;_12};
You can also remove items from the cart:
_12import { useCart, useCartItem } from '@vtex/checkout';_12_12const RemoveItemExample = () => {_12 const cart = useCart();_12 const cartItem = useCartItem();_12_12 const removeItem = () => cart.removeItem({_12 originalIndex: cartItem.originalIndex_12 });_12_12 return <button onClick={removeItem}>Remove from cart</button>;_12};
Parameters
The useCart hook does not accept any parameters.
Returns
The useCart hook returns an object with the following properties:
items
items: CartItem[]
The current list of items in the cart.
addItem
addItem: (data: AddItemData) => Promise<void>
The AddItemData type is an object with the following structure:
_10type AddItemData = {_10 quantity: number;_10 id: string;_10 seller: string;_10};
removeItem
removeItem: (data: RemoveItemData) => Promise<void>
The RemoveItemData type is an object with the following structure:
_10type RemoveItemData = {_10 originalIndex: number;_10};
Extension Points
This hook is available in the following Checkout extension points:
cart.cart-list.beforecart.cart-list.aftercart.cart-item.aftercart.assembly-options.button.after