Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorporated mycart with session storage #48

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions assets/js/Home.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,17 @@ listProductHTML.addEventListener('click', (event) => {
});

const addCartToMemory = () => {
localStorage.setItem('cart', JSON.stringify(carts));
const loggedInUser = sessionStorage.getItem('loggedInUser');

if (loggedInUser) {
// Parse the user object
const user = JSON.parse(loggedInUser);

// Store the cart items in sessionStorage under the user's identifier
sessionStorage.setItem(`cart_${user.username}`, JSON.stringify(carts));
} else {
console.error('No user is logged in. Cannot save cart to session storage.');
}
};

const addCartToHTML = () => {
Expand Down Expand Up @@ -144,9 +154,21 @@ const changeQuantity = (productId, type) => {
};

const initApp = () => {
if (localStorage.getItem('cart')) {
carts = JSON.parse(localStorage.getItem('cart'));
addCartToHTML();
const loggedInUser = sessionStorage.getItem('loggedInUser');

if (loggedInUser) {
// Parse the user object
const user = JSON.parse(loggedInUser);

// Retrieve the user's cart from sessionStorage
const userCart = sessionStorage.getItem(`cart_${user.username}`);

if (userCart) {
carts = JSON.parse(userCart);
addCartToHTML();
}
} else {
console.error('No user is logged in. Cannot initialize cart from session storage.');
}
};

Expand Down
Loading