please help , we have a product with automatically gets added to cart when few selected products are added to cart, our requirement is that able to remove that automatically added product from cart if its the only product left in the cart , my present code is working fine , but sometime this product wont be automatically remove unless i refresh the page , it seams like code is working but cart is nit updating sometimes , please do help
document.addEventListener(‘DOMContentLoaded’, function() {
setInterval(function() {
// Fetch the cart data from Shopify’s API
fetch(‘/cart.js’)
.then(response => {
if (!response.ok) {
throw new Error(‘Network response was not ok’);
}
return response.json();
})
.then(cart => {
console.log(“Cart fetched:”, cart); // Log the cart contents
// Check if there is only one product in the cart
if (cart.items.length === 1) {
console.log(“Only one product in the cart”);
// Check if the product handle matches the desired one
if (cart.items[0].handle === “SELECTED-PRODUCT-HANDLE”) {
console.log(“Product handle matches”);
// Clear the cart
fetch(‘/cart/clear.js’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’
}
})
.then(response => {
if (!response.ok) {
throw new Error(‘Failed to clear the cart’);
}
return response.json();
})
.then(updatedCart => {
console.log(“Cart cleared:”, updatedCart);
// Integrate the cart update functionality here
// window.location.reload();
const body = JSON.stringify({
updates: {}, // No items in the cart after clear
sections: ‘mini-cart’ // Specify any section you want to update
});
fetch(window.routes.cart_update_url, { …fetchConfig(), …{ body } })
.then((response) => response.text())
.then((responseText) => {
dispatchCartEvent(
JSON.parse(responseText).sections,
‘mini-cart’
);
})
.catch((error) => console.log(‘Error updating cart after clear:’, error));
// Add a slight delay before fetching the cart again
setTimeout(() => {
fetch(‘/cart.js’)
.then(response => {
if (!response.ok) {
throw new Error(‘Failed to fetch updated cart’);
}
return response.json();
})
.then(freshCart => {
console.log(“Updated cart after clearing:”, freshCart);
// Optionally reload or update UI here
// window.location.reload(); // Force reload to ensure cart is reflected
})
.catch(error => console.error(‘Error fetching updated cart:’, error));
}, 500); // Adjust delay if needed
})
.catch(error => console.error(‘Error clearing cart:’, error));
} else {
console.log(“Product handle does not match.”);
}
} else {
console.log(“Cart has more than one product or is empty.”);
}
})
.catch(error => console.error(‘Error fetching cart data:’, error));
}, 1000); // Check every second (1000ms)
});