I’ve got an issue with my custom Shopify Dawn theme. I built a new add-to-cart button for a special template. It adds products correctly, but the cart drawer doesn’t update until I refresh the page. I tried using a function from the cart.js file to update the cart, yet it fails to work. Here is the function I’m using:
function refreshCartContents() {
if (this.element.id === 'cart-drawer-items') {
fetchAndUpdateSection('cart-drawer')
.then(updateDrawerElements)
.catch(logError);
} else {
fetchAndUpdateSection('main-cart-items')
.then(updateMainCartItems)
.catch(logError);
}
}
function fetchAndUpdateSection(sectionId) {
return fetch(`?section_id=${sectionId}`).then(res => res.text());
}
function updateDrawerElements(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
['cart-drawer-items', '.cart-drawer__footer'].forEach(selector => {
replaceElement(selector, doc);
});
}
function updateMainCartItems(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const newItems = doc.querySelector('cart-items');
this.element.innerHTML = newItems.innerHTML;
}
function replaceElement(selector, doc) {
const oldEl = document.querySelector(selector);
const newEl = doc.querySelector(selector);
if (oldEl && newEl) oldEl.replaceWith(newEl);
}
function logError(e) {
console.error('Cart update failed:', e);
}
I also checked the server response, which returns a bunch of HTML indicating an empty cart. Does anyone have suggestions on how to resolve this?