Troubleshooting · Developer docs

Troubleshooting

Grouped by symptom, never by module, because the person with the problem does not know which module has it. One hundred questions across ten pages, each answered with the causes in the order they usually turn out to be true.

Answer Commerce

The cart count is wrong or stale

  1. It is rendered on a cached page. A count printed with $_cart in a site-wide header is stored with the page and served to every later visitor, so they see the first visitor's count. Reading $_cart also saves an empty cart for every visitor, crawlers included. Render the count in the browser from the API (the cart widget must be a fragment).
  2. It counts the wrong thing. Decide whether the badge shows lines or units, and leave out unavailable items, which are not in the total or the checkout.
  3. It is not updated after a change. Every cart call returns the whole cart. Update the count from that response, rather than reloading something that may be cached.
  4. The page came back from the browser's back-forward cache, with the count as it was when the shopper left. Refresh it on pageshow.
JavaScript
async function refreshCartCount() {
  const res = await fetch('/cdna-api/cart', { headers: { Accept: 'application/json' } });
  const items = res.ok ? (await res.json()).data.cart.items : [];  // 404: no cart yet
  const count = items
    .filter(item => item.available)
    .reduce((total, item) => total + item.quantity, 0);
  document.querySelectorAll('[data-cart-count]').forEach(el => { el.textContent = count; });
}
refreshCartCount();
window.addEventListener('pageshow', event => { if (event.persisted) refreshCartCount(); });

More in Commerce

  1. A discount code is rejected for no visible reason
  2. Shipping rates do not appear at checkout
  3. Tax is calculated as zero
  4. A payment succeeded but no order exists
  5. A test payment method is selectable on production

Was this page helpful?

Your answer goes to the docs team.