ShoppingCart Class
Understanding the core ShoppingCart class that powers use-shopping-cart v4.0.
Overview
The ShoppingCart class is the heart of use-shopping-cart v4.0. It manages all cart state and provides methods for cart operations using a pub/sub pattern.
Public API
class ShoppingCart {
constructor(config?: CartConfig)
getState(): Readonly<CartState>
getInitialState(): Readonly<CartState>
subscribe(callback: (state: CartState) => void): () => void
addItem(product: Product, options?: AddItemOptions): void
incrementItem(id: string, options?: IncrementOptions): void
decrementItem(id: string, options?: IncrementOptions): void
setItemQuantity(id: string, quantity: number): void
removeItem(id: string): void
clearCart(): void
loadCart(cartDetails: CartDetailsInput, shouldMerge?: boolean): void
handleCartClick(): void
handleCartHover(): void
handleCloseCart(): void
storeLastClicked(id: string): void
changeCurrency(currency: string): void
changeLanguage(language: string): void
}State
Every change replaces the state object instead of mutating it, so getState() returns a new object after each change and the same object otherwise. That's what lets useShoppingCart (built on useSyncExternalStore) skip re-renders when nothing changed.
getInitialState() returns the state built from config alone: your cartDetails, currency, and language (en-US if you don't set one), without the saved cart or the browser's language. It's the same on the server and in the browser, so useShoppingCart renders it on the server and while hydrating, then switches to getState(). Until something changes the cart, both return the same object.
cartCount, totalPrice, formattedTotalPrice and each entry's value, formattedValue and formattedPrice are recomputed whenever the cart entries, currency or language change. They're plain fields on the state, not getters.
Subscribing
const unsubscribe = cart.subscribe((state) => {
console.log('Cart changed!', state.cartCount)
})
cart.addItem(product)
cart.removeItem(product.id)
unsubscribe()Subscribers are called synchronously after every change, with the new state.
Persistence
With shouldPersist on (the default) and in a browser, the cart:
- Loads the saved cart from
storageunderpersistKeywhen it's created. With an async adapter, the saved cart is applied when the Promise resolves. If cart entries changed in the meantime, the saved cart is skipped; a currency or language set in the meantime is kept, and the saved entries are still restored. - Saves
cartDetails,currencyandlanguage(plus the totals) whenever the cart entries, currency or language change. Changes made together in the same task are saved once, right after it. With an async storage adapter, nothing is saved until the saved cart has loaded. Opening the cart orstoreLastClickeddoesn't write to storage. - Ignores saved data it can't parse, and drops entries that aren't valid cart entries.
See Persistence for adapters and examples.
Error Handling
Invalid input throws a CartError and leaves the cart unchanged. Branch on error.code rather than the message:
import { ShoppingCart, isCartError } from 'use-shopping-cart/core'
try {
cart.incrementItem(id)
} catch (error) {
if (isCartError(error) && error.code === 'ITEM_NOT_IN_CART') {
cart.addItem(product)
} else {
throw error
}
}Use isCartError(error) rather than instanceof CartError: each entry point (use-shopping-cart, /core, /utilities) bundles its own copy of the class, so instanceof fails across them.
| Code | Thrown by |
|---|---|
INVALID_PRODUCT | addItem and addToCartAction with a product missing name, price or currency |
INVALID_COUNT | a count that isn't a positive integer |
INVALID_QUANTITY | a quantity that isn't a non-negative integer (or positive, in validateCartItems) |
ITEM_NOT_IN_CART | incrementItem, decrementItem, setItemQuantity, removeItem with an ID not in the cart |
INVALID_FORM_DATA | useCartActions forms with missing or unreadable fields |
INVALID_INVENTORY | validateCartItems with an inventory that isn't a list of objects |
INVALID_CART | loadCart and validateCartItems with malformed cartDetails |
NOT_IN_INVENTORY | validateCartItems with a cart entry that isn't in the inventory |
INVALID_CHECKOUT_URL | redirectToCheckout with anything other than an http(s) session URL |
NO_CART_PROVIDER | useShoppingCart and the other hooks outside <CartProvider> |
NOT_IN_BROWSER | redirectToCheckout called on the server |
UNKNOWN | only in useCartActions state, for errors that aren't CartErrors |
Testing
The class is easily testable:
import { ShoppingCart } from 'use-shopping-cart/core'
test('adds item to cart', () => {
const cart = new ShoppingCart({
currency: 'USD',
shouldPersist: false
})
const product = {
id: 'test_1',
name: 'Test Product',
price: 1000,
currency: 'USD'
}
cart.addItem(product)
expect(cart.getState().cartCount).toBe(1)
expect(cart.getState().totalPrice).toBe(1000)
})Direct Usage (Advanced)
While most users use useShoppingCart(), you can use the class directly:
import { ShoppingCart } from 'use-shopping-cart/core'
const cart = new ShoppingCart({
currency: 'USD'
})The constructor takes a CartConfig:
| Option | Default | Description |
|---|---|---|
cartDetails | {} | Initial cart entries; totals are computed from them |
currency | 'USD' | ISO 4217 currency code |
language | navigator.language | Language for formatting |
shouldPersist | true | Save the cart to storage |
persistKey | 'use-shopping-cart' | Storage key |
storage | localStorage | A StorageAdapter |
Config options aren't part of getState(). getState() returns cartDetails, cartCount, totalPrice, formattedTotalPrice, currency, language, shouldDisplayCart and lastClicked.
// Subscribe to changes
cart.subscribe((state) => {
updateUI(state)
})
// Use cart methods
cart.addItem(product)
cart.incrementItem('product_id')
cart.clearCart()See Also
- Architecture - Overall architecture
- Persistence - How persistence works
- useShoppingCart - React hook wrapper
