How to delete cart item after other item has been deleted

Hi,

Adding custom javascript can help .

Code example(theme.liquid)

function removeItemFromCart(itemId, callback) {
  fetch('/cart/change.js', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
    body: JSON.stringify({
      id: itemId,
      quantity: 0
    })
  })
  .then(response => response.json())
  .then(data => {
    if (typeof callback === 'function') {
      callback(data);
    }
  })
  .catch(error => console.error('Error:', error));
}

function handleCartUpdates() {
  fetch('/cart.js')
    .then(response => response.json())
    .then(data => {
      const cartItems = data.items;
      let itemToRemove = null;
      
      cartItems.forEach(item => {
        // Add your condition to check which item should be removed
        // For example, remove item B if item A is removed
        if (/* condition to identify item to remove */) {
          itemToRemove = item;
        }
      });
      
      if (itemToRemove) {
        removeItemFromCart(itemToRemove.id, (response) => {
          console.log('Removed item:', response);
        });
      }
    });
}

// Call handleCartUpdates when appropriate
document.addEventListener('DOMContentLoaded', handleCartUpdates);
1 Like