useCart
The useCart hook allows you to access cart data and perform mutations that will reflect on other entities within the Sales App data layer.
Usage
import { useCart } from '@vtex/sales-app'
const TotalItems = () => {const cart = useCart()
return <div>Items: {cart.items.length}</div>
}Additionally, you can use useCart to interact with the Sales App data layer by mutating the cart items list:
import { useCart } from '@vtex/sales-app'
const TotalItems = () => {const cart = useCart()
const addItem = () => cart.addItem({ quantity: 1, seller: '1', id: '8392' })
return <button onClick={addItem}>Add to cart</button>
}Parameters
The useCart hook does not receive any parameters.
Returns
The useCart hook returns an object with the following properties:
orderFormId
- type
orderFormId: string | undefined
value
- type
value: number
items
- type:
CartItem[]
totalizers
- type
Totalizers[]
clientProfileData
- type:
ClientProfileData
addItem
- type:
addItem: (data: UseCartAddItemData) => Promise<void>
The UseCartAddItemData type is an object with the following structure:
type UseCartAddItemData = { id: string; quantity: number; seller: string; attachments?: Attachment[];};removeItem
- type
removeItem: (id: string, index: number) => Promise<void>
addCoupon
- type
addCoupon: (coupon: string) => Promise<void>
sync
Syncs the cart with the latest data from the Order Form. This is useful to ensure that the cart reflects any changes made outside Sales App.
- type
sync: () => Promise<void>
Extension Points
This hook is available in the following extension points:
cart.cart-list.aftercart.cart-item.aftercart.order-summary.afterpdp.sidebar.beforepdp.sidebar.afterpdp.content.after
For a full list of available extension points, refer to the ExtensionPoints page.