I have built my e-commerce application, I have API registration and login working(request and response) . I have have API for different products, I have favorites and shopping cart with item totals as well as total amount. I have local storage working for login and I have tested session storage as well, its working. My question is how do I tie everything together meaning when the user logs in how do I associate them to a particular cart. I’m stuck here. So when a different user logs in if the cart is empty it should show that if a cart has something in it, it should show how many items they have. That’s the way I have my code set up. Can someone please explain this to me or point me in the right direction
Thanking You In Advance
2
Answers
I suggest that you can use local storage to save all data then you can post that to backend by API once you have a API.
It’s a bit confusing question. What I understood is OP wants to get the cart details for a logged-in user. If this is the question, then in simple terms,
There should be a relation between these entities. Assuming you use a relational database i.e. Mysql/Postgres etc. you’ll have a user table, product table, session table, and cart table. All of these tables should have relations between them. For simplicity, let’s say the relation can be based on a user id.
So, in the user table, there’ll be a row with the user id and the other details. For the same user id, there will be a row (or many rows, depending on the design) in the cart table.
So, when a user logs in, you can request in the cart API to get the cart for the user. And in your data layer (where you will get the data from the database), it is basically like the following,
This will give you the cart details i.e. which products and how many products are in the cart, when the cart was updated/added etc.
And, if the user is not logged in and can still add items to the cart, you can store that in your local storage in the front end. And when the user wants to check out, you can ask them to log in and when they do, you can post the cart data (living inside your local storage) to the cart POST API to add a new entry. (It’s a long design. I am trying to give you a hint here)