- It is rendered on a cached page. A count printed with
$_cartin a site-wide header is stored with the page and served to every later visitor, so they see the first visitor's count. Reading$_cartalso 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). - 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.
- 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.
- 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.
Answer
Commerce
The cart count is wrong or stale
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
Was this page helpful?
Your answer goes to the docs team.