I’m working on a React e-commerce site and I’m having trouble keeping items in the cart when a user logs out. I want the products to remain in the database for each user even after they log out. I suspect the issue might be related to the size
variable, but I’m not completely sure how to resolve it.
I’ve tried updating the MongoDB schema, but the changes are not reflected. Here is my current user model:
const UserSchema = new mongoose.Schema({
name: String,
email: { type: String, unique: true },
password: String,
cartData: {
type: Map,
of: {
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 }
}
},
createdAt: { type: Date, default: Date.now }
});
const User = mongoose.model('User', UserSchema);
My add to cart function is structured as follows:
const addToCart = async (productId, size) => {
try {
const response = await fetch('/api/cart/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({ productId, size })
});
const data = await response.json();
if (data.success) {
updateCartState(productId, size);
}
} catch (error) {
console.error('Failed to add item to cart:', error);
}
};
Any suggestions on how to ensure that cart items persist after logout? Thanks!