SO im trying to get the products selected to appear in my Cart Page even if a I log out of the account, that they stay in the database for the respective user. But i think is because of the variable size that impeeding that, I was trying to add but being novice in react and mongo db failed.
I tried changing the db but atlas on my websitedidn’t update…
The mongo db code as of now
//Create API for user
const Users = mongoose.model('Users', {
name:{
type: String,
},
email:{
type: String,
unique:true,
},
password:{
type:String,
},
cartData:{
type:Object,
},
date:{
type:Date,
default:Date.now,
}
})
And I changed it to this in my back end
const Users = mongoose.model('Users', {
name: {
type: String,
},
email: {
type: String,
unique: true,
},
password: {
type: String,
},
cartData: {
type: Map,
of: {
type: Object,
default: {
S: { type: Number, default: 0 },
M: { type: Number, default: 0 },
L: { type: Number, default: 0 },
XL: { type: Number, default: 0 },
XXL: { type: Number, default: 0 },
},
},
},
date: {
type: Date,
default: Date.now,
},
});
My addtocart API
// Endpoint to add products to cart data
app.post('/addtocart', fetchUser, async (req, res) => {
console.log("added", req.body.jerseyId);
try {
const { jerseyId } = req.body;
if (!jerseyId) {
return res.status(400).json({ error: "Item ID is required" });
}
let userData = await Users.findOne({ _id: req.user.id });
// Initialize the item in the cart if it doesn’t exist
if (!userData.cartData[jerseyId]) {
userData.cartData[jerseyId] = 0;
}
userData.cartData[jerseyId] += 1;
await Users.findOneAndUpdate({ _id: req.user.id }, { cartData: userData.cartData });
res.json({ success: true, message: "Item added to cart successfully" });
} catch (error) {
console.error("Error adding item to cart:", error);
res.status(500).json({ success: false, message: "An error occurred while adding the item to the cart" });
}
});
front-end that calls API
const addToCart = (jerseyId, size) => {
setCartItems((prev) => ({
...prev,
[jerseyId]: {
...prev[jerseyId],
[size]: (prev[jerseyId][size] || 0) + 1, // Increment the quantity for the selected size
},
}));
if (localStorage.getItem('auth-token')) {
fetch('http://localhost:4000/addtocart', {
method: 'POST',
headers: {
Accept: 'application/json',
'auth-token': localStorage.getItem('auth-token'),
'Content-Type': 'application/json',
},
body: JSON.stringify({ jerseyId, size }), // Now sending both jerseyId and size
})
.then(response => response.json())
.then(data => console.log(data));
}
};
How cart page look (just in case)
import React, { useContext } from 'react';
import './CartItems.css'; // Importing the CSS file for styling.
import { ShopContext } from '../../Context/ShopContext'; // Importing ShopContext to access cart-related functions and data.
import remove_icon from '../Assets/remove_icon.jpg'; // Remove item icon.
const CartItems = () => {
const { getTotalCartAmount, every_product, cartItems, removeFromCart } = useContext(ShopContext); // Accessing cart context.
return (
<div className='cartitems'>
{/* Header row for cart item details */}
<div className="cartitems-format-main">
<p>Products</p>
<p>Title</p>
<p>Size</p> {/* Added Size column */}
<p>Price</p>
<p>Quantity</p>
<p>Total</p>
{/* <p>Remove</p> */}
</div>
<hr />
{/* Mapping over the products to display each cart item */}
{every_product.map((e) => {
// Check if there is any item of this product in the cart for any size
const productInCart = Object.keys(cartItems[e.id]).filter(size => cartItems[e.id][size] > 0);
// Only display products with a quantity greater than 0 for any size
return productInCart.length > 0 ? (
<div key={e.id}>
{productInCart.map((size) => (
<div className="cartitems-format cartitems-format-main" key={size}>
{/* Product image */}
<img
src={e.image || 'default_image_path.jpg'}
alt={e.name}
className='carticon-product-icon'
/>
<p>{e.name}</p> {/* Product name */}
<p>{size}</p> {/* Display selected size */}
<p>${e.us_cost}</p> {/* Product price */}
{/* Quantity button */}
<button className='cart-items-quantity'>
{cartItems[e.id][size]} {/* Display quantity for the selected size */}
</button>
{/* Total price for the product based on quantity and size */}
<p>${e.us_cost * cartItems[e.id][size]}</p>
{/* Remove from cart button */}
<img
src={remove_icon}
onClick={() => removeFromCart(e.id, size)}
alt="Remove item"
className='cart-items-remove-icon'
/>
</div>
))}
<hr />
</div>
) : null; // Explicitly return null if no items for this product
})}
{/* Section for cart total and checkout */}
<div className="cart-items-down">
<div className="cartitems-total">
<h1>Totals</h1>
<div>
{/* Subtotal */}
<div className="cartitems-total-item">
<p>Subtotal</p>
<p>${getTotalCartAmount()}</p> {/* Total cost of all items in the cart */}
</div>
<hr />
{/* Shipping fee */}
<div className="cartitems-total-item">
<p>Shipping Fee</p>
<p>Free Shipping!</p>
</div>
<hr />
{/* Grand total */}
<div className="cartitems-total-item">
<h3>Total</h3>
<h3>${getTotalCartAmount()}</h3> {/* Grand total after shipping */}
</div>
</div>
{/* Proceed to checkout button */}
<button className="cart-items-checkout-button">PROCEED TO CHECKOUT</button>
</div>
</div>
</div>
);
};
export default CartItems;