Documentation
Feedback
Guides
API Reference

Guides
Guides

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


_10
import { useCart } from '@vtex/checkout';
_10
_10
const 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:


_12
import { useCart } from '@vtex/checkout';
_12
_12
const 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:


_12
import { useCart, useCartItem } from '@vtex/checkout';
_12
_12
const 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:


_10
type 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:


_10
type RemoveItemData = {
_10
originalIndex: number;
_10
};

Extension Points

This hook is available in the following Checkout extension points:

  • cart.cart-list.before
  • cart.cart-list.after
  • cart.cart-item.after
  • cart.assembly-options.button.after
Contributors
1
Photo of the contributor
Was this helpful?
Yes
No
Suggest Edits (GitHub)
Contributors
1
Photo of the contributor
Was this helpful?
Suggest edits (GitHub)
On this page