loadCart()
Loads a previously saved cart, enabling cart persistence across devices or sessions. Useful for logged-in users.
Signature
loadCart(cartDetails: CartDetailsInput, shouldMerge?: boolean): voidParameters
cartDetails- The cart entries to load, keyed by product id. Each entry needs a stringid,nameandcurrency, a finiteprice, and aquantitythat's an integer greater than 0.value,formattedValue,formattedPriceandtimestampare optional:valueand the formatted fields are recomputed, and a missingtimestampis set to now. TheCartDetailsInputandCartEntryInputtypes describe this shape; aCartDetailsobject from the cart fits it tooshouldMerge- Whether to merge with current cart (default:true)true- Combines loaded cart with current cartfalse- Replaces current cart entirely (recommended)
Basic Usage
import { useEffect } from 'react'
import { useShoppingCart } from 'use-shopping-cart'
function App() {
const { loadCart } = useShoppingCart()
useEffect(() => {
// Load cart from your API
async function loadUserCart() {
const response = await fetch('/api/cart')
const savedCart = await response.json()
if (savedCart) {
loadCart(savedCart, false) // Replace current cart
}
}
loadUserCart()
}, [loadCart])
return <YourApp />
}Load Cart on User Login
import { useEffect } from 'react'
import { useShoppingCart } from 'use-shopping-cart'
import { useUser } from './auth'
function CartSync() {
const { loadCart } = useShoppingCart()
const user = useUser()
useEffect(() => {
if (!user?.id) return
let cancelled = false
async function syncCart() {
const response = await fetch(`/api/users/${user.id}/cart`)
const userCart = await response.json()
if (!cancelled && userCart) {
loadCart(userCart, false)
}
}
syncCart()
return () => {
cancelled = true
}
}, [user?.id, loadCart])
return null
}Save Cart on Changes
Post cartDetails itself, so your endpoint can return it as-is to the examples above:
import { useEffect } from 'react'
import { useShoppingCart } from 'use-shopping-cart'
function CartPersistence() {
const { cartDetails } = useShoppingCart()
const user = useUser()
useEffect(() => {
if (!user?.id) return
// Debounce saves
const timeoutId = setTimeout(() => {
fetch(`/api/users/${user.id}/cart`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(cartDetails)
})
}, 500)
return () => clearTimeout(timeoutId)
}, [cartDetails, user?.id])
return null
}Notes
- Recommended: Set
shouldMergetofalseto avoid accidental duplicate merging - Typically used with user authentication systems
- Throws a
CartErrorwith codeINVALID_CART, and leaves the cart unchanged, ifcartDetailsisn't an object or an entry is missing one of the fields above - Don't call it inside
useOptimisticCart'sonChangewith a cart that already includes the change: the change is applied afteronChangeresolves, so it would count twice (see useOptimisticCart) - Works alongside localStorage persistence (for logged-out users)
See Also
- Persistence - How cart persistence works
- shouldPersist - localStorage persistence
