Documentation
Feedback
Guides
Storefront Development

Storefront Development
FastStore
useCart
The useCart hook gives access to the Cart object and helper functions for managing the shopping cart. The hook allows adding, removing, and updating items in the cart and checking its status (e.g., whether it is empty or validating).

Import


_10
import { useCart } from '@faststore/sdk'

Usage

The following example demonstrates how the items array is mapped to display the name and price of each item in the cart:

_13
function Cart () {
_13
const { items, isValidating } = useCart()
_13
_13
return (
_13
<>
_13
{items.map(item => (
_13
<div>name: {item.itemOffered.name}</div>
_13
<div>Price: {item.price}</div>
_13
))}
_13
<a href="/checkout">{isValidating ? 'loading...' : 'Checkout'}</a>
_13
</>
_13
)
_13
}

The isValidating flag is used to show a loading state while the cart is being validated.

API reference

The useCart hook returns an object with the following properties and functions:
Variable nameTypeDescription
addItem(item: T) => voidAdds an item to the cart.
emptyCart() => voidRemoves all items from the cart.
getItem`(id: string) => Tundefined`
idstringGets the cart's unique identifier.
inCart(id: string) => booleanChecks if an item with the given id exists in the cart.
isEmptybooleanReturns true if the cart is empty.
isValidatingbooleanReturns true if the cart is being validated (e.g., syncing with a server).
itemsItem[]Gets the current items in the cart.
removeItem(id: string) => voidRemoves an item from the cart by its id.
setCart(cart: Cart) => voidReplaces the current cart with a new one.
updateItemQuantity(id: string, quantity: number) => voidUpdates the quantity of a given item in the cart.
Contributors
1
Photo of the contributor
Was this helpful?
Yes
No
Suggest Edits (GitHub)
Contributors
1
Photo of the contributor
On this page