Create Cart Flow
This document provides a step-by-step guide for implementing the Create Cart flow in your React application. This flow ensures that every product is added to a valid cart and manages cart creation, validation, and item manipulation.
Overview
The flow covers the following main steps:
- Check if a valid cart exists
- Create a cart if it doesn't exist
- Store the cart locally
- Add products to the cart
- Handle cart updates and deletion
Prerequisites
- The user must be logged in
Implementation
1. Checking for an Existing Cart
Before adding a product to the cart, check if a valid cart already exists by using the getCart API.
// cart.ts
const checkOrCreateCart = async () => {
const existingCartId = localStorage.getItem("cartId");
if (existingCartId) {
const cart = await getCart();
const isValid = cart?.id === existingCartId;
if (isValid) return existingCartId;
}
// No valid cart found, so create a new one
const newCartId = await createCart();
localStorage.setItem("cartId", newCartId);
return newCartId;
};
getCart– Retrieves cart data.createCart– Creates a new cart and returns acartId.
2. Adding a Product to the Cart
Once you have a valid cartId, you can add the selected product to the cart.
// cart.ts
const addToCart = async (productId: string, quantity: number, price: number) => {
const cartId = await checkOrCreateCart();
await addProductToCart(cartId, productId, quantity, price);
console.log("✅ Product added to cart");
};
addProductToCart– Adds the given product to the cart.
3. Removing an Item from the Cart
To remove a specific item from the cart:
// cart.ts
const removeItem = async (itemId: string) => {
const cartId = localStorage.getItem("cartId");
if (!cartId) return;
await removeItemFromCart(cartId, itemId);
console.log("🗑 Item removed");
};
removeItemFromCart– Removes an item from the cart based on its ID.
4. Deleting the Cart
You may need to clear the entire cart, for example, after checkout or logout:
// cart.ts
const deleteCartFlow = async () => {
const cartId = localStorage.getItem("cartId");
if (!cartId) return;
await deleteCart(cartId);
localStorage.removeItem("cartId");
console.log("Cart deleted");
};
deleteCart– Deletes the entire cart from the backend.
Notes
- Always validate the cart before using it to prevent acting on stale or deleted data.
- Store the
cartIdsecurely in localStorage or your preferred storage mechanism. - You can also persist the cart in the backend using user tokens if needed.