I’ve basically got an ajax call where I’m adding multiple products to cart via one event.
The products are added to an array like this
let crossSellSelected = false
const crossSellElements = productFormContainer?.querySelectorAll('.crossSell__Item.selected');
let crossSell
let crossSellArray = new Array();
if (crossSellElements) {
crossSellSelected = true
crossSellElements.forEach(crossSellElement => {
const selectedCrossSell = crossSellElement.querySelector('.crossSell__Swatch.selected .crossSell__Radio').value
crossSell = {
id: selectedCrossSell,
quantity: 1
}
crossSellArray.push(crossSell)
})
}
They are then converted to json and added in an ajax call like this
const response = await fetch(
`${window.themeVariables.routes.cartAddUrl}.js?sections=mini-cart`,
{
body: JSON.stringify({
items: crossSellSelected
? [crossSellArray, product]
: [product],
attributes: {
_ttp: getCookie("_ttp"),
ttclid: getCookie("ttclid"),
},
}),
method: "POST",
headers: {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
},
},
);
But the post method fails in this case. However if I change it to
const response = await fetch(
`${window.themeVariables.routes.cartAddUrl}.js?sections=mini-cart`,
{
body: JSON.stringify({
items: crossSellSelected
? [crossSellArray[0], product]
: [product],
attributes: {
_ttp: getCookie("_ttp"),
ttclid: getCookie("ttclid"),
},
}),
method: "POST",
headers: {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
},
},
);
it works. So it looks to me the issue is that it is an array but I’m not really sure why that is an issue and how to fix it. Any help would be greatly appreciated
>Solution :
I think using spread operator will do the job:
change this:
[crossSellArray, product]
To this:
[...crossSellArray, product]