I am back with another question regarding the add-to-cart feature within the Prestige theme. I would like to create a basket of products and when the add to cart button is clicked add each product to the cart. This is what I have so far:
addToCart() {
let items = [];
this.slots.forEach(slot => {
items.push({
'id': slot.id,
'quantity': 1
});
});
console.log(items);
fetch('/cart/add.js', {
body: JSON.stringify({ 'items': items }),
credentials: 'same-origin',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest' // This is needed as currently there is a bug in Shopify that assumes this header
}
})
.then(response => {
return response.json();
})
.catch((error) => {
console.error('Error:', error);
});
}
I get the items in my console.log correctly. But I am getting /cart/add.js 404 (Not Found). Is there a more performant way of doing this that plays nice with this theme?
This is strange because the variant ids are correct. So the idea behind this was to create a basket of products. Then add this basket of products to the cart.
Iâm guessing that this should be incrementing the product quantity of a product that has been added more than once instead of adding a new item entry?
let items = [];
this.slots.forEach(slot => {
items.push({
'id': slot.id,
'quantity': 1
});
});
fetch('/cart/add.js', {
body: JSON.stringify({ 'items': items }),
credentials: 'same-origin',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest' // This is needed as currently there is a bug in Shopify that assumes this header
}
}).then(response => {
document.dispatchEvent(new CustomEvent('theme:loading:end'));
if (response.ok) {
document.querySelector( '.add-to-cart' ).removeAttribute('disabled');
this.dispatchEvent(new CustomEvent('product:added', {
bubbles: true
}));
} else {
response.json().then(function (content) {
const errorMessageElement = document.createElement('span');
errorMessageElement.className = 'ProductForm__Error Alert Alert--error';
errorMessageElement.innerHTML = content['description'];
document.querySelector( '.add-to-cart' ).removeAttribute( 'disabled' );
document.querySelector( '.add-to-cart' ).insertAdjacentElement( 'afterend', errorMessageElement );
setTimeout(function () {
errorMessageElement.remove();
}, 2500);
});
}
});
When I click the â.add-to-cartâ button I get the error: âCannot Find Variantâ. These variants exist. If I were to go into the admin > products and plug this ID in I get my product/variant:
Thank you for your response. It was actually the ID that was trying to pass along. Instead of using the âvariantâ id as the documentation says I was passing the âproductâ id. So like the error said that variant could not be found.