Overview
The Music Store shopping cart is built using React’s Context API, providing a centralized state management solution for cart operations across the application.CartContext Provider
The cart functionality is provided through theCartProvider component, which wraps the application and makes cart operations available to all child components.
Implementation
src/context/CartContext/CartContext.jsx
State Management
The cart maintains two pieces of state:carrito
Array of products with their quantities. Each product includes all product data plus a
cantidad field.carritoAbierto
Boolean that controls the visibility of the cart panel. Automatically opens when products are added.
Available Functions
agregarProducto
Adds a product to the cart or increments its quantity if it already exists.- Checks if the product already exists in the cart by comparing IDs
- If exists: increments the
cantidadby 1 - If new: adds the product with
cantidad: 1 - Automatically opens the cart panel (
setCarritoAbierto(true))
quitarProducto
Removes a product completely from the cart.id(number): The product ID to remove
cambiarCantidad
Adjusts the quantity of a product in the cart.id(number): The product IDdelta(number): The amount to change (+1 to increase, -1 to decrease)
- Uses
Math.max(1, p.cantidad + delta)to ensure quantity never goes below 1 - To remove a product completely, use
quitarProductoinstead
Cart State
Accessing Cart Data
Available Cart Properties
Available Cart Properties
- carrito: Array of products with quantities
- carritoAbierto: Boolean for panel visibility
- setCarritoAbierto: Function to manually toggle cart panel
- agregarProducto: Add or increment product
- quitarProducto: Remove product completely
- cambiarCantidad: Adjust product quantity
- total: Computed total price of all items
Total Calculation
The cart automatically calculates the total price:precio by its cantidad and sums the results.
Usage Example
Here’s how the cart is used in the ProductoDetalle component:src/components/productos/ProductosDetalle.jsx
The cart panel automatically opens when a product is added, providing immediate visual feedback to the user.
Product Data Structure
Products in the cart contain the following fields:cantidad field is automatically added when products are placed in the cart.