Part 78: Building a Shopping Cart Feature with React and API Integration
[Pages] Shopping Cart (Exercises)

In our ongoing project, we've integrated React Query to handle client-side data fetching, and we've set up authentication to enable user-specific features. Now, we're ready to add a crucial element to our application: a shopping cart. This feature will allow users to add products to their personal carts, enhancing their shopping experience. Let's explore how to implement this functionality and interact with a backend API to manage cart items.
Understanding the Cart Items Collection
Our backend uses a database to store cart items, with each entry representing a product added by a user. Here's a breakdown of the fields for each cart item:
User: A reference to the user who owns the cart.
Product: A reference to the product added to the cart.
Quantity: The number of units of the product.
Let's walk through how to interact with this data using an API.
Fetching Cart Items
To display cart items on the front end, we need to retrieve them from the server. This requires authentication, as each user should only see their own cart items. Here's how you can fetch cart items using an API request:
Authentication: Ensure your request includes a valid token, typically obtained during user login.
GET Request: Send a
GETrequest to/cart-itemswith the authentication token to receive the cart data.
Example Code for Fetching Cart Items
// File: api/cart.js
import { fetchJson } from '../lib/api';
export async function fetchCartItems(token) {
const response = await fetchJson('/api/cart-items', {
headers: {
'Authorization': `Bearer ${token}`,
},
});
return response;
}Adding Items to the Cart
To add a product to the cart, you'll need to make a POST request to the API. This request must include the product ID and quantity, and it requires authentication to associate the item with the correct user.
Example Code for Adding Cart Items
// File: api/cart.js
export async function addCartItem(token, productId, quantity) {
const response = await fetchJson('/api/cart-items', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
product: productId,
quantity,
}),
});
return response;
}Integrating with React
With the backend API ready, we can integrate these functionalities into our React application. We'll add an "Add to Cart" button on each product page and a "Cart" page to display the user's cart items.
Adding "Add to Cart" Button
In the product page component, we can use the addCartItem function to handle adding products to the cart.
// File: components/ProductPage.js
import React from 'react';
import { addCartItem } from '../api/cart';
function ProductPage({ product, token }) {
const handleAddToCart = async () => {
try {
await addCartItem(token, product.id, 1);
alert('Product added to cart!');
} catch (error) {
console.error('Error adding to cart:', error);
}
};
return (
<div>
<h1>{product.name}</h1>
<button onClick={handleAddToCart}>Add to Cart</button>
</div>
);
}
export default ProductPage;Displaying Cart Items
On the cart page, use the fetchCartItems function to retrieve and display the user's cart items.
// File: components/CartPage.js
import React, { useEffect, useState } from 'react';
import { fetchCartItems } from '../api/cart';
function CartPage({ token }) {
const [cartItems, setCartItems] = useState([]);
useEffect(() => {
const loadCartItems = async () => {
try {
const items = await fetchCartItems(token);
setCartItems(items);
} catch (error) {
console.error('Error fetching cart items:', error);
}
};
loadCartItems();
}, [token]);
return (
<div>
<h1>Your Cart</h1>
<ul>
{cartItems.map(item => (
<li key={item.id}>
{item.product.name} - Quantity: {item.quantity}
</li>
))}
</ul>
</div>
);
}
export default CartPage;Conclusion
By implementing a shopping cart feature, we've enhanced our application to support user-specific functionality. This involved setting up API interactions for fetching and adding cart items, and integrating these capabilities into our React components. As you continue to develop your application, remember to leverage these techniques to build a robust and user-friendly shopping experience.
Last updated