Initializes the cart by loading an existing cart from session storage or creating a new one.
You must call init() before using any other cart methods.
Parameters
None
Returns
Promise<ShopifyCart>
Examples
Basic initialization
await shoppy.cart.init()
console.log('Cart ready:', shoppy.cart.count(), 'items')
Initialize on page load
document.addEventListener('DOMContentLoaded', async () => {
await shoppy.init({
token: 'your-token',
storeDomain: 'your-store.myshopify.com'
})
await shoppy.cart.init()
})
With subscription
// Subscribe before init to catch the initial state
shoppy.cart.subscribe((cart) => {
updateCartUI(cart)
})
await shoppy.cart.init()
Behavior
- Checks
sessionStorage for an existing cart ID
- If found, fetches the cart from Shopify
- If not found (or cart expired), creates a new cart
- Stores the cart ID in
sessionStorage
- Notifies all subscribers with the cart state