Skip to main content

Cart Management Quick Start

This quick-start guide walks you through the essential steps for implementing a complete cart lifecycle in your Elastic Path storefront application.

Prerequisites

  • A JavaScript application with Elastic Path SDK installed
  • @epcc-sdk/sdks-shopper package configured with your client credentials
npm install @epcc-sdk/sdks-shopper

Step 1: Initialize the Cart

The first step is to either create a new cart or retrieve an existing one using the SDK's built-in initializeCart utility:

import { initializeCart } from "@epcc-sdk/sdks-shopper";

// Get or create a cart ID
const cartId = await initializeCart();

This utility handles both first-time visitors and returning customers by checking for a previously stored cart ID.

Step 2: Add Items to Cart

Add products to the cart using the manageCarts method:

import { manageCarts, getCartId } from "@epcc-sdk/sdks-shopper";

// Add a product to cart
const addToCart = async (productId, quantity = 1) => {
const cartId = getCartId();

if (!cartId) {
throw new Error("No cart found");
}

const response = await manageCarts({
path: {
cartID: cartId,
},
body: {
data: {
type: "cart_item",
id: productId,
quantity: quantity,
},
},
});

return response.data;
};

Step 3: Update Item Quantities

Modify quantities of items already in the cart:

import { updateACartItem, getCartId } from "@epcc-sdk/sdks-shopper";

// Update quantity of an item in the cart
const updateItemQuantity = async (itemId, newQuantity) => {
const cartId = getCartId();

if (!cartId) {
throw new Error("Cart not found");
}

const response = await updateACartItem({
path: {
cartID: cartId,
cartitemID: itemId,
},
body: {
data: {
id: itemId,
quantity: newQuantity,
},
},
});

return response.data;
};

Step 4: Calculate Cart Totals

Retrieve the cart with totals information:

import { getCart, getCartId } from "@epcc-sdk/sdks-shopper";

// Get cart with totals
const getCartWithTotals = async () => {
const cartId = getCartId();

if (!cartId) {
throw new Error("No cart found");
}

const response = await getCart({
path: {
cartID: cartId,
},
query: {
include: ["items"], // Include cart items in the response
},
});

// Extract pricing information
const pricing = response.data?.data?.meta?.display_price;
if (pricing) {
console.log("Cart totals:", {
subtotal: pricing.without_discount?.formatted,
discount: pricing.discount?.formatted,
tax: pricing.tax?.formatted,
total: pricing.with_tax?.formatted,
});
}

return response.data;
};

Step 5: Place an Order

Complete the cart lifecycle by converting it to an order:

import { checkoutACart, getCartId } from "@epcc-sdk/sdks-shopper";

// Checkout a cart to create an order
const placeOrder = async (customerData) => {
const cartId = getCartId();

if (!cartId) {
throw new Error("No cart found");
}

const response = await checkoutACart({
path: {
cartID: cartId,
},
body: {
data: {
customer: customerData.customer,
billing_address: customerData.billingAddress,
shipping_address: customerData.shippingAddress,
},
},
});

// Clear the cart ID after successful order
localStorage.removeItem("ep_cart_id");

return response.data;
};

Complete Cart Flow Example

Here's how you might implement a complete cart flow in a React component:

import React, { useEffect, useState } from "react";
import { getCart, initializeCart, getCartId } from "@epcc-sdk/sdks-shopper";

function CartExample() {
const [cart, setCart] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);

// Fetch cart data from API
const fetchCart = async () => {
try {
setLoading(true);
const cartId = getCartId();

if (!cartId) {
setError("No cart found");
return null;
}

const response = await getCart({
path: { cartID: cartId },
query: { include: ["items"] },
});

setCart(response.data);
return response.data;
} catch (err) {
setError("Failed to fetch cart");
console.error(err);
return null;
} finally {
setLoading(false);
}
};

// Initialize or fetch cart on component mount
useEffect(() => {
const loadCart = async () => {
try {
setLoading(true);

// Use the SDK's initializeCart utility
const cartId = await initializeCart();

// Fetch full cart data
const response = await getCart({
path: { cartID: cartId },
query: { include: ["items"] },
});

setCart(response.data);
} catch (err) {
setError("Failed to initialize cart");
console.error(err);
} finally {
setLoading(false);
}
};

loadCart();
}, []);

// Add product to cart
const handleAddToCart = async (productId, quantity = 1) => {
try {
setLoading(true);
await addToCart(productId, quantity);
await fetchCart(); // Refresh cart data
} catch (err) {
setError("Failed to add product");
} finally {
setLoading(false);
}
};

// Update item quantity
const handleUpdateQuantity = async (itemId, quantity) => {
try {
setLoading(true);
await updateItemQuantity(itemId, quantity);
await fetchCart(); // Refresh cart data
} catch (err) {
setError("Failed to update quantity");
} finally {
setLoading(false);
}
};

return (
<div>
{/* Cart UI implementation */}
{loading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
{cart && (
<div>
<h2>Your Cart</h2>
{/* Render cart items and totals */}
</div>
)}
</div>
);
}

Next Steps

Now that you've implemented a basic cart lifecycle, explore these advanced topics:

tip

For a complete example, check out the SPA Cart Example in the Elastic Path Composable Frontend repository.