I am trying to add more than 100 products to cart using add.js but is unable to do so, if I try to add 150 products to cart only 100 gets added for some reason. Here is the code I am using -
function addToCart(variantIds) {
const batchSize = 50;
const batches = [];
// Split the variant IDs into batches of batchSize
for (let i = 0; i < variantIds.length; i += batchSize) {
const batch = variantIds.slice(i, i + batchSize);
batches.push(batch);
}
// Define a function to add a single batch to the cart
function addBatch(batch) {
const data = {
items: batch.map(variantId => {
return {
id: variantId,
quantity: 1
};
})
};
fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
return response.json();
})
.then(data => {
// Wait for 500ms before adding the next batch
setTimeout(() => {
addNextBatch();
}, 500);
})
.catch(error => {
console.error(error);
});
}
// Define a function to add the next batch to the cart
function addNextBatch() {
if (batches.length > 0) {
const batch = batches.shift();
addBatch(batch);
} else {
// If all batches have been added, redirect to the cart page
window.location.href = '/cart';
}
}
// Start adding batches from the first batch
addNextBatch();
}