Skip to content

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

src/index.tsx
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:

src/index.tsx
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:

src/index.tsx
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

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.before
  • cart.cart-list.after
  • cart.cart-item.after
  • cart.assembly-options.button.after

For a full list of available extension points, refer to the ExtensionPoints page.