Hey All,
Reading the Cart API reference docs (Cart API reference), and was wondering if you can:
- send more than one item per POST? ie 2x ID/Quantity?
- can you send other keys in the POST, such as line_price etc?
- if you need to send one item per POST, does cart/add.js need to await or could I run something in parallel (ie: something like this):
await Promise.all(
validItems.map(item =>
fetch('/cart/add.js', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(item)
})
)
);
Cheers
Chris
You can send a list of items in the request for example.
{
'items': [{
'id': 36110175633573,
'quantity': 2
},{
'id': 12345,
'quantity': 2
}]
};
You shouldn’t need to Promise.all and map over each item, because you can just send a list of items.
You should await each request to add to ensure the carts valid and you don’t duplicate items.
You can’t add any other top level properties to this, but you can add extra line item properties / custom attributes as mentioned here Cart API reference
Hey @ChrisBradley, as @JordanFinners shared you can add multiple line items to the cart at once using the Cart API. You could also do so directly within a product form without using any JS if you would prefer to go that route (for example, if they are going to be taken to the cart page after the form has processed).
That said, you will want to wait until it has processed to do things like refreshing a cart drawer or checking logic to add mor line items for automatic BOGO or GWP.
Really interesting, I tried and it didnt work so I must have missed something. I’ll give it another go. thanks!
1 Like
Hey @RobDukarski
I did consider adjusting the product form to support multiple ltems on the add.
I decided to keep it seperate so that the overall cart logic remains vanilla and inline with horizon’s standard form logic and I can keep this as a standalone block that can be inserted without changing other parts of the theme.
1 Like