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
_10import { 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:
_13function 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 name | Type | Description |
---|---|---|
addItem | (item: T) => void | Adds an item to the cart. |
emptyCart | () => void | Removes all items from the cart. |
getItem | `(id: string) => T | undefined` |
id | string | Gets the cart's unique identifier. |
inCart | (id: string) => boolean | Checks if an item with the given id exists in the cart. |
isEmpty | boolean | Returns true if the cart is empty. |
isValidating | boolean | Returns true if the cart is being validated (e.g., syncing with a server). |
items | Item[] | Gets the current items in the cart. |
removeItem | (id: string) => void | Removes an item from the cart by its id . |
setCart | (cart: Cart) => void | Replaces the current cart with a new one. |
updateItemQuantity | (id: string, quantity: number) => void | Updates the quantity of a given item in the cart. |