Skip to content

useCartPunchout

The useCartPunchout 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 { useCartPunchout } from '@vtex/checkout'
const TotalItems = () => {
const cart = useCartPunchout()
return <div>Items: {cart.items.length}</div>
}

Additionally, you can use useCartPunchout to interact with the Checkout data layer by mutating the cart items list:

src/index.tsx
import { useCartPunchout } from '@vtex/checkout'
const TotalItems = () => {
const cart = useCartPunchout()
const addItem = () => cart.addItem({
quantity: 1,
seller: '1',
id: '8392'
})
return <button onClick={addItem}>Add to cart</button>
}

We do not support everything that the Checkout API supports in core, if you do x action in the Checkout API directly. After performing some action in the Checkout API, you can call the sync method to update the the screen. This is useful when you want to ensure that the UI reflects the latest state of the cart after making changes through other means. (e.g.: Add shipping info using the endpoint /api/checkout/pub/orderForm/{orderFormId}/attachments/shippingData).

src/index.tsx
import { useCartPunchout } from '@vtex/checkout'
const MyComponent = () => {
const cart = useCartPunchout()
const handleClick = async() => {
// Performs some interaction with some VTEX API
await cart.sync();
}
return <button onClick={handleClick}>Add to cart</button>
}

Parameters

The useCartPunchout hook does not receive any parameters.

Returns

The useCartPunchout 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;
};

};

sync

  • type: sync: () => Promise<void>

Extension Points

This hook is available in the following extension points:

  • punchout.cart-item.after

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