При перезагрузке /products в серверной части django создается несколько сеансов
Код: Выделить всё
[16/Sep/2024 17:11:31] "GET /api/products/ HTTP/1.1" 200 212
Session key: iedrvaus89536ly57pb242tnalwtx7vo
[16/Sep/2024 17:11:31] "GET /api/carts/retrieve_cart/ HTTP/1.1" 200 107
[16/Sep/2024 17:11:31] "GET /api/products/ HTTP/1.1" 200 212
Session key: eipxdrmkf343fjtkchk7ads14ef1vccr
[16/Sep/2024 17:11:31] "GET /api/carts/retrieve_cart/ HTTP/1.1" 200 107
Код: Выделить всё
{
"id": 77,
"items": [
{
"id": 66,
"product": 1,
"product_sku": "MNT-MST-MDL-HRV",
"product_name": "Monthly Harvest Box",
"product_price": 50.0,
"quantity": 1
}
],
"created_at": "2024-09-16T20:10:24.950541Z",
"updated_at": "2024-09-16T20:10:24.950541Z"
},
{
"id": 78,
"items": [],
"created_at": "2024-09-16T20:10:25.006548Z",
"updated_at": "2024-09-16T20:10:25.006548Z"
}
Код: Выделить всё
import React, { useState, useEffect } from "react";
import './ProductsPage.css';
import Cart from './Cart';
import PictureGrid from "./PictureGrid";
const ProductsPage = () => {
const [products, setProducts] = useState([]);
const [cartItems, setCartItems] = useState([]);
const [cart, setCart] = useState(null); // Cart starts as null
const [total, setTotal] = useState(0);
const [loadingCart, setLoadingCart] = useState(true); // For managing loading state
// Fetch products from the Django API
useEffect(() => {
fetch('http://localhost:8000/api/products/')
.then(response => response.json())
.then(data => setProducts(data))
.catch(error => console.error('Error fetching products:', error));
}, []);
// Retrieve or create the cart for the current session
useEffect(() => {
if (!cart) {
loadCart(); // Load the cart for the current session
}
}, [cart]);
// Load cart items for the current session
const loadCart = () => {
setLoadingCart(true); // Set loading state to true while loading cart
fetch(`http://localhost:8000/api/carts/retrieve_cart/`)
.then(response => response.json())
.then(cartData => {
setCart(cartData.id); // Set the cart ID
setCartItems(cartData.items); // Set cart items
calculateTotal(cartData.items); // Calculate the total
setLoadingCart(false); // Set loading state to false after loading cart
})
.catch(error => {
console.error('Error fetching cart data:', error);
setLoadingCart(false); // Set loading state to false even if there's an error
});
};
// Calculate total price of the cart
const calculateTotal = (items) => {
const totalPrice = items.reduce((sum, item) => {
const itemPrice = parseFloat(item.product_price);
return sum + (itemPrice * item.quantity);
}, 0);
setTotal(totalPrice);
};
// Function to handle adding a product to the cart
const addToCart = (productSku) => {
if (!cart) {
console.error('Cart not defined yet. Try again later.');
return;
}
console.log('Adding product with SKU:', productSku);
fetch(`http://localhost:8000/api/carts/${cart}/add_item`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ sku: productSku, quantity: 1 }),
})
.then(response => response.json())
.then(data => {
console.log('Product added to cart:', data);
// Reload the cart after adding the item
loadCart();
})
.catch(error => console.error('Error adding product to cart:', error));
};
// Function to handle removing a product from the cart
const removeFromCart = (productSku) => {
if (!cart) {
console.error('Cart not defined yet. Try again later.');
return; // Prevent the function from running if cart is not yet defined
}
console.log('Removing product with SKU:', productSku);
fetch(`http://localhost:8000/api/carts/${cart}/remove_item/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ sku: productSku }),
})
.then(response => {
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
return response.json();
})
.then(data => {
console.log('Item removed from cart:', data);
const updatedCartItems = cartItems.filter(item => item.product_sku !== productSku);
setCartItems(updatedCartItems); // Update the cart items after removal
calculateTotal(updatedCartItems); // Recalculate the total
})
.catch(error => console.error('Error removing item from cart:', error));
};
return (
Our Subscriptions
{products.map(product => (
[img]{[/img]
{product.name}
Price: ${product.price}
addToCart(product.sku)} disabled={loadingCart}>
{loadingCart ? 'Loading...' : 'Add to Cart'}
SKU: {product.sku}
))}
{/* Include the Cart component */}
);
};
export default ProductsPage;
Подробнее здесь: https://stackoverflow.com/questions/789 ... -duplicate