Persistent shopping cart across sessions in React e-commerce app

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!

Hey there! Your e-commerce project sounds really interesting. Have you thought about using JWT (JSON Web Tokens) for authentication? They’re super handy for maintaining user sessions across multiple visits.

For the cart persistence, maybe you could try a hybrid approach? Store the cart data in both localStorage and your MongoDB. When a user logs in, you could merge their localStorage cart with their database cart. That way, even if they add items while logged out, everything syncs up when they log back in.

Just curious, how are you handling product inventory? It’d be cool to see how you’re managing stock levels when items are in carts but not yet purchased. Any thoughts on implementing a time limit for items in carts?

Keep us posted on how it goes! E-commerce apps can be tricky, but they’re so rewarding when you get them right. :blush:

For persistent shopping carts, I’d recommend using a combination of server-side storage and client-side caching. Store the cart data in your MongoDB as you’re doing, but also implement a session-based approach. When a user logs in, fetch their cart data from the database and store it in their session. On logout, save the session cart data back to the database. This way, you maintain persistence across sessions while also having real-time cart updates. For the client-side, you could use React’s Context API or Redux to manage the cart state, ensuring it’s updated whenever changes occur. This approach has worked well in my experience with e-commerce projects.

hey dancingbutterfly, i’ve faced similar issues before. have u considered using localstorage to store cart data? it persists even after browser closes. you could sync it with the server when user logs in/out. just remember to handle potential conflicts between local and server data. good luck with ur project!