-
Customer Panel
-
document.addEventListener('alpine:init', () => {
Alpine.data('app', () => ({
appCart: {
items: [],
updateLocalStorage: function () {
localStorage.setItem('cart', JSON.stringify(this.items));
},
set: function (items) {
this.items = items;
this.updateLocalStorage();
},
add: function (productId, variantId, quantity) {
const item = this.items.find((item) => item.variantId === variantId);
if (item) {
item.quantity += quantity;
} else {
this.items.push({ productId, variantId, quantity });
}
this.updateLocalStorage();
},
remove: function (variantId) {
this.items = this.items.filter((item) => item.variantId !== variantId);
this.updateLocalStorage();
},
editQuantity: function (variantId, quantity) {
const item = this.items.find((item) => item.variantId === variantId);
item.quantity = quantity;
this.updateLocalStorage();
},
get countWithQuantities() {
return this.items.reduce((acc, item) => acc + item.quantity, 0);
},
init: function () {
if (localStorage.getItem('cart')) {
try {
this.items = JSON.parse(localStorage.getItem('cart'));
if (!Array.isArray(this.items)) {
this.items = [];
}
} catch (error) {
console.error('Error parsing cart from local storage', error);
this.items = [];
}
}
}
},
init: function () {
this.appCart.init();
}
}));
});