useCart
The useCart hook allows you to access cart data and perform mutations that will reflect on other entities within the Checkout data layer.
Usage
import { useCart } from '@vtex/checkout'
const TotalItems = () => { const cart = useCart()
return <div>Items: {cart.items.length}</div>}Additionally, you can use useCart to interact with the Checkout data layer by mutating the cart items list:
import { useCart } from '@vtex/checkout'
const AddItemExample = () => { const cart = useCart() const addItem = () => cart.addItem({ quantity: 1, seller: '1', id: '8392' })
return <button onClick={addItem}>Add to cart</button>}You can also remove items from the cart:
import { useCart, useCartItem } from '@vtex/checkout'
const RemoveItemExample = () => { const cart = useCart() const cartItem = useCartItem()
const removeItem = () => cart.removeItem({ originalIndex: cartItem.originalIndex })
return <button onClick={removeItem}>Remove from cart</button>}Parameters
The useCart hook does not receive any parameters.
Returns
The useCart hook returns an object with the following properties:
items
- type:
CartItem[]
addItem
- type:
addItem: (data: AddItemData) => Promise<void>
The AddItemData type is an object with the following structure:
type AddItemData = { quantity: number; id: string; seller: string;};removeItem
- type:
removeItem: (data: RemoveItemData) => Promise<void>
The RemoveItemData type is an object with the following structure:
type RemoveItemData = { originalIndex: number;};Extension Points
This hook is available in the following extension points:
cart.cart-list.beforecart.cart-list.aftercart.cart-item.aftercart.assembly-options.button.after
For a full list of available extension points, refer to the ExtensionPoints page.