Fix cart initialization and ShopifyCart loading

- Wait for ShopifyCart to be available before initializing structured data
- Add getCart() method to retrieve existing cart from Shopify API
- Load cart state on page load to display correct initial cart contents

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
isUnknown 2026-01-21 11:06:28 +01:00
parent 9396ae4e02
commit aa873e117f
3 changed files with 83 additions and 6 deletions

View file

@ -32,6 +32,9 @@
// Initialize event listeners
setupEventListeners();
// Load initial cart state
loadCart();
}
function setupEventListeners() {
@ -60,6 +63,18 @@
});
}
async function loadCart() {
if (!cartInstance) return;
try {
const cart = await cartInstance.getCart();
currentCart = cart;
renderCart();
} catch (error) {
console.error('Error loading cart:', error);
}
}
function openDrawer() {
drawer.classList.add('is-open');
document.body.style.overflow = 'hidden';

View file

@ -306,6 +306,58 @@ class ShopifyCart {
return cart;
}
/**
* Get existing cart by ID
*/
async getCart() {
if (!this.cartId) {
return null;
}
const query = `
query getCart($cartId: ID!) {
cart(id: $cartId) {
id
checkoutUrl
lines(first: 10) {
edges {
node {
id
quantity
merchandise {
... on ProductVariant {
id
title
price {
amount
currencyCode
}
product {
title
}
}
}
}
}
}
}
}
`;
try {
const data = await this.query(query, {
cartId: this.cartId
});
return data.cart;
} catch (error) {
// Cart might be expired or invalid
console.error('Error fetching cart:', error);
this.clearCart();
return null;
}
}
/**
* Get checkout URL to redirect user
*/

View file

@ -38,12 +38,18 @@
const language = container.dataset.language || 'fr';
const isEnglish = language === 'en';
const cart = new ShopifyCart({
domain: 'nv7cqv-bu.myshopify.com',
storefrontAccessToken: 'dec3d35a2554384d149c72927d1cfd1b'
});
function initStructuredData() {
if (typeof ShopifyCart === 'undefined') {
setTimeout(initStructuredData, 100);
return;
}
cart.getProductByHandle(handle).then(product => {
const cart = new ShopifyCart({
domain: 'nv7cqv-bu.myshopify.com',
storefrontAccessToken: 'dec3d35a2554384d149c72927d1cfd1b'
});
cart.getProductByHandle(handle).then(product => {
if (!product) return;
const title = isEnglish && product.titleEn?.value ? product.titleEn.value : product.title;
@ -79,6 +85,10 @@
if (schemaScript) {
schemaScript.textContent = JSON.stringify(schema, null, 2);
}
});
});
}
// Initialize when ShopifyCart is available
initStructuredData();
})();
</script>