Blog>
Snippets

Implementing Add to Cart Functionality

Illustrates how to implement add-to-cart functionality, including updating the cart state and quantity of products using TanStack Store.
import { createStore } from '@tanstack/react-store';

// Define initial store state
const initialState = {
    items: [], // Array to hold cart items
    totalQuantity: 0, // Total number of items in cart
};

// Create a store with the initial state
export const cartStore = createStore({
    initialState,
});
Initializes the cart store using TanStack's createStore. The cart includes an items array for the products added to the cart and a totalQuantity for tracking the total items.
// Function to add a product to the cart
export function addToCart(product, quantity) {
    cartStore.setState((state) => {
        const existingItemIndex = state.items.findIndex(item => item.id === product.id);
        const existingItem = state.items[existingItemIndex];
        let updatedItems;

        if (existingItem) {
            const updatedItem = {...existingItem, quantity: existingItem.quantity + quantity};
            updatedItems = [...state.items];
            updatedItems[existingItemIndex] = updatedItem;
        } else {
            updatedItems = state.items.concat({...product, quantity});
        }

        return {
            ...state,
            items: updatedItems,
            totalQuantity: state.totalQuantity + quantity
        };
    });
}
Defines an addToCart function to handle adding products to the cart. It checks if the product already exists in the cart and updates its quantity; otherwise, it adds the new product. It also updates the totalQuantity in the cart.