I am using this code to add an item to the shopify cart
let formData = {
'items': [
{ 'id': {{ product.selected_or_first_available_variant.id }}, 'quantity': 1 },
]
};
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
return response.json();
})
.then(data => {
console.log('Success:', data);
// Add any additional logic here, e.g., updating the cart UI
})
.catch((error) => {
console.error('Error:', error);
});
The issue is that {{ product.selected_or_first_available_variant.id }} doesn’t automatically update. I have to refresh/reload page before it works. Any help would be greatly appreciated. Thanks!