I have a some JS on my Shopify site that pulls in data from cart.js using Fetch API to update the checkout link URL parameters based on the items and quantity. I need this function to run again every time Cart.js is updated. Can anyone help me out?
function updateCartButton() {
// Fetch Cart JSON from Shopify
const cartJson = '/cart.js';
async function getCartJson() {
fetch(cartJson)
.then((res) => {
return res.json();
})
.then((data) => {
// Get Product Info from Shopify
let productInfo = data.items;
console.log(productInfo);
// Create URL Params Array
let urlParamsArray = [];
const createURL = () => {
productInfo.forEach(object => {
const urlParams = `${object.sku}.${object.quantity}`;
urlParamsArray.push(urlParams);
})
}
createURL()
console.log(urlParamsArray);
// Join URL Params into One String
let urlParamsJoin = urlParamsArray.join('_');
console.log(urlParamsJoin);
// Get Checkout Button from Cart
const checkoutBtn = document.querySelector('.cart__submit');
console.log(checkoutBtn);
// Add URL Params to Checkout Button
checkoutBtn.href = `https://cleannutra.pay.clickbank.net/?cbskin=38436&cbitems=` + `${urlParamsJoin}`;
});
}
getCartJson();
}
updateCartButton();