I have created a cart for buying service subscription. The user can select from 4 different customer options. All have the same item name offcourse.
I need to prevent the user from buying two different subscriptions in the same cart. for example he adds the Monthly subscription the he adds the quaterly one. In this case they will appear as two differnt items in the cart. This is what i want to prevent.
I trying to monitor events like item.adding and too check for the product name, although the validation confirmed it is the same product and I returned false , the action continued and the product is added to the cart
// adding item event
window.Snipcart.events.on('item.adding', (parsedCartItem: any) => {
console.log("adding the following item: ", parsedCartItem);// Check if the item belongs to "Product1 Options"
console.log("parsedCartItem.name:", parsedCartItem.name);
// Check if the item belongs to "Product1 Options"
if (parsedCartItem.name === 'Product1') {
// Get the current items in the cart
const currentItems = window.Snipcart.store.getState().cart.items.items;
console.log("currentItems: ", currentItems);
// Find if there's already a "Product1 Options" item in the cart
const existingItem = currentItems.find((item: any) => item.name === 'Product1');
if (existingItem) {
console.log('A "Product1" is already in the cart.');
// Prevent adding another "Product1 Options" item
if (existingItem.id !== parsedCartItem.id) {
console.log('Cannot add another "Product1" item.');
return false;
}
}
}
// If none of the conditions to cancel the addition are met, return true to allow the item to be added
console.log("adding item conditions met");
return true;
});