Hi everyone !
I’m new to Shopify.
Based on theme Dawn, I have created a snippet that automatically add to cart a gift product, if cart total >= 100$, and remove gift is cart total < 100.
The problem is that I have to reload the page once to see the gift added to cart, twice to update the cart count bubbles. How to update efficiently my cart without reloading?
Thanks for your help !
Here is my code :
// assets/free-gift.js
document.addEventListener("DOMContentLoaded", function () {
const settings = window.freeGiftSettings;
const giftProductId = settings.giftProductId;
const minimumCartValue = settings.minimumCartValue;
let giftAdded = false;
function updateCartDrawer() {
const drawerItems = document.querySelector('cart-drawer-items');
if (drawerItems && typeof drawerItems.onCartUpdate === 'function') {
drawerItems.onCartUpdate();
} else {
document.dispatchEvent(new Event('cart:updated'));
}
}
function checkCartForGift() {
fetch("/cart.js")
.then(response => response.json())
.then(cart => {
let cartTotal = cart.total_price;
let giftItem = cart.items.find(item => item.id === giftProductId);
if (cartTotal >= minimumCartValue && !giftItem && !giftAdded) {
addGiftToCart();
} else if (cartTotal < minimumCartValue && giftItem) {
removeGiftFromCart(giftItem.key);
}
});
}
function addGiftToCart() {
fetch("/cart/add.js", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
items: [{
id: giftProductId,
quantity: 1,
properties: { is_gift: true }
}],
})
})
.then(response => {
if (!response.ok) {
throw new Error("Erreur lors de l'ajout du cadeau");
}
giftAdded = true;
return fetch("/cart.js");
})
.then(res => res.json())
.then(cart => {
const cartData = cart.items;
document.dispatchEvent(new CustomEvent('cart:refresh', {
bubbles: true,
detail: cartData
}));
updateCartDrawer();
updateCartBubble();
updateCartUI();
})
.catch(error => console.error("Erreur lors de l'ajout du cadeau :", error));
}
function removeGiftFromCart(itemKey) {
fetch("/cart/change.js", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id: itemKey,
quantity: 0
})
})
.then(response => {
if (!response.ok) throw new Error("Erreur lors du retrait du cadeau");
giftAdded = false;
return fetch("/cart.js");
})
.then(response => response.json())
.then(cart => {
const cartData = cart.items;
document.dispatchEvent(new CustomEvent('cart:refresh', {
bubbles: true,
detail: cartData
}));
updateCartDrawer();
updateCartBubble();
updateCartUI();
})
.catch(error => console.error("Erreur lors du retrait du cadeau :", error));
}
function updateCartUI() {
document.dispatchEvent(new Event('cart:updated'));
}
function updateCartDrawer() {
document.querySelector('cart-drawer').dispatchEvent(new Event('cart:open'));
}
function updateCartBubble() {
fetch('/?sections=cart-icon-bubble')
.then(res => res.json())
.then(data => {
const cartBubble = document.querySelector('[data-cart-icon-bubble]');
if (cartBubble && data['cart-icon-bubble']) {
cartBubble.innerHTML = data['cart-icon-bubble'];
}
})
.catch(error => console.error("Erreur lors de la mise à jour du cart bubble :", error));
}
document.addEventListener("cart:updated", checkCartForGift);
checkCartForGift();
});