Cart Methods
The next object provides complete programmatic control over the shopping cart.
Initialization
Section titled “Initialization”// Check if SDK is readyif (window.next) { // SDK ready, use it directly next.addItem({ packageId: 123 });} else { // Queue for later execution window.nextReady = window.nextReady || []; window.nextReady.push(function() { next.addItem({ packageId: 123 }); });}Adding Items
Section titled “Adding Items”addItem
Section titled “addItem”Adds an item to the cart. Requires an options object.
// ✅ CORRECT - Pass an object with packageIdawait next.addItem({ packageId: 123, quantity: 2});
// ✅ Quantity is optional (defaults to 1)await next.addItem({ packageId: 123 });
// ❌ WRONG - Don't pass packageId directly// next.addItem(123); // This won't work!Parameters:
options.packageId(number): Package ID to addoptions.quantity(number, optional): Quantity to add (default: 1)
Returns: Promise<void>
Removing Items
Section titled “Removing Items”removeItem
Section titled “removeItem”Removes an item from the cart completely.
await next.removeItem({ packageId: 123 });Parameters:
options.packageId(number): Package ID to remove
Returns: Promise<void>
clearCart
Section titled “clearCart”Empties the entire cart.
await next.clearCart();Returns: Promise<void>
Updating Quantities
Section titled “Updating Quantities”updateQuantity
Section titled “updateQuantity”Sets the quantity for a specific item.
await next.updateQuantity({ packageId: 123, quantity: 5});
// Set to 0 to removeawait next.updateQuantity({ packageId: 123, quantity: 0});Parameters:
options.packageId(number): Package ID to updateoptions.quantity(number): New quantity
Returns: Promise<void>
Swapping Items
Section titled “Swapping Items”swapCart
Section titled “swapCart”Replace entire cart contents in one operation.
await next.swapCart([ { packageId: 123, quantity: 1 }, { packageId: 456, quantity: 2 }, { packageId: 789, quantity: 1 }]);Parameters:
items(Array): New cart itemspackageId(number): Package IDquantity(number): Quantity
Returns: Promise<void>
This is useful for:
- Restoring saved carts
- Applying preset bundles
- Bulk cart operations
Checking Cart State
Section titled “Checking Cart State”hasItemInCart
Section titled “hasItemInCart”Check if a specific item is in the cart.
const hasItem = next.hasItemInCart({ packageId: 123 });if (hasItem) { console.log('Item is in cart');}Parameters:
options.packageId(number): Package ID to check
Returns: boolean
getCartCount
Section titled “getCartCount”Get total number of items in cart.
const count = next.getCartCount();console.log(`Cart has ${count} items`);Returns: number
getCartData
Section titled “getCartData”Get comprehensive cart information.
const cartData = next.getCartData();console.log(cartData);// {// cartLines: [...], // Enriched items with product data// cartTotals: {...}, // Pricing breakdown// campaignData: {...}, // Campaign configuration// appliedCoupons: [...] // Active discounts// }Returns:
{ cartLines: EnrichedCartLine[]; cartTotals: CartTotals; campaignData: Campaign | null; appliedCoupons: AppliedCoupon[];}getCartTotals
Section titled “getCartTotals”Get just the pricing information.
const totals = next.getCartTotals();console.log('Subtotal:', totals.subtotal.formatted); // "$89.99"console.log('Shipping:', totals.shipping.formatted); // "$10.00"console.log('Tax:', totals.tax.formatted); // "$8.00"console.log('Discount:', totals.discount.formatted); // "-$10.00"console.log('Total:', totals.total.formatted); // "$97.99"Returns:
{ subtotal: { raw: number, formatted: string }, shipping: { raw: number, formatted: string }, tax: { raw: number, formatted: string }, discount: { raw: number, formatted: string }, total: { raw: number, formatted: string }}Common Patterns
Section titled “Common Patterns”Add to Cart with Options
Section titled “Add to Cart with Options”// Clear cart and add new itemawait next.clearCart();await next.addItem({ packageId: 123, quantity: 1 });
// Or use data attributes for the same effect```html<button data-next-action="add-to-cart" data-next-package-id="123" data-next-clear-cart="true"> Buy Now</button>Toggle Item in Cart
Section titled “Toggle Item in Cart”async function toggleItem(packageId) { if (next.hasItemInCart({ packageId })) { await next.removeItem({ packageId }); } else { await next.addItem({ packageId }); }}
// Usageawait toggleItem(123);Quantity Increment/Decrement
Section titled “Quantity Increment/Decrement”async function incrementQuantity(packageId, step = 1) { const cart = next.getCartData(); const currentItem = cart.cartLines.find( line => line.packageId === packageId );
if (currentItem) { await next.updateQuantity({ packageId, quantity: currentItem.quantity + step }); } else { await next.addItem({ packageId, quantity: step }); }}
// Increment by 1await incrementQuantity(123);
// Increment by 5await incrementQuantity(123, 5);
// Decrement by 1await incrementQuantity(123, -1);Reactive Cart Updates
Section titled “Reactive Cart Updates”// Listen for cart changesnext.on('cart:updated', (cartState) => { // Update UI document.querySelector('.cart-count').textContent = next.getCartCount();
document.querySelector('.cart-total').textContent = cartState.totals.total.formatted;
// Show/hide empty cart message const emptyMessage = document.querySelector('.empty-cart'); if (cartState.isEmpty) { emptyMessage.style.display = 'block'; } else { emptyMessage.style.display = 'none'; }});
// React to specific actionsnext.on('cart:item-added', (data) => { showNotification(`Added ${data.item.title} to cart`);});
next.on('cart:item-removed', (data) => { showNotification(`Removed item from cart`);});Batch Operations
Section titled “Batch Operations”async function addMultipleItems(items) { // Add items sequentially for (const item of items) { await next.addItem(item); }
// Or replace entire cart at once await next.swapCart(items);}
// Usageawait addMultipleItems([ { packageId: 123, quantity: 1 }, { packageId: 456, quantity: 2 }, { packageId: 789, quantity: 1 }]);Save and Restore Cart
Section titled “Save and Restore Cart”// Save cart statefunction saveCartState() { const cartData = next.getCartData(); const cartItems = cartData.cartLines.map(line => ({ packageId: line.packageId, quantity: line.quantity }));
localStorage.setItem('savedCart', JSON.stringify(cartItems));}
// Restore cart stateasync function restoreCartState() { const saved = localStorage.getItem('savedCart'); if (saved) { const items = JSON.parse(saved); await next.swapCart(items); localStorage.removeItem('savedCart'); }}
// UsagesaveCartState(); // Before checkoutawait restoreCartState(); // On returnError Handling
Section titled “Error Handling”try { await next.addItem({ packageId: 999999 });} catch (error) { console.error('Failed to add item:', error.message); // Show user-friendly error showError('Unable to add item to cart. Please try again.');}
// Listen for global errorsnext.on('error:occurred', (error) => { console.error('Cart error:', error); // Log to error tracking service});TypeScript Support
Section titled “TypeScript Support”import type { CartItem, CartTotals, Campaign } from '@next-commerce/sdk';
// Type-safe cart operationsasync function addProduct(packageId: number, quantity: number = 1): Promise<void> { await next.addItem({ packageId, quantity });}
// Type-safe cart datafunction displayCart(): void { const data = next.getCartData(); const totals: CartTotals = data.cartTotals; console.log(totals.total.formatted);}Performance Tips
Section titled “Performance Tips”- Batch updates when possible - Use
swapCartfor multiple changes - Use events for UI updates - Don’t poll for cart state
- Cache cart data - Store
getCartData()result if using multiple times - Debounce quantity updates - Wait for user to finish typing
// Debounced quantity updatelet updateTimer;function debounceQuantityUpdate(packageId, quantity) { clearTimeout(updateTimer); updateTimer = setTimeout(async () => { await next.updateQuantity({ packageId, quantity }); }, 500);}Related Documentation
Section titled “Related Documentation”- Events - React to cart changes
- Data Attributes - HTML-based cart control
- Coupon Methods - Apply discounts
- Shipping Methods - Set delivery options