Add to Cart
Adds an item to cart
Description
The addToCart() action adds a specific product or variant to the user’s active shopping cart inside the app.
It works seamlessly with the native Vajro cart and triggers a cartUpdated event once the item is added successfully.
You can use this action from any custom block, PDP extension, or embedded web view to provide a smooth “Add to Cart” experience without reloading the page.
Function Signature
VajroSDK.actions.addToCart([
{
variantId: "12345",
quantity: 1,
sellingPlanId: "1234234342", // Optional
attributes: [{ "key":"custom_key","value":"custom_value"}] // Optional
},
])| Parameter | Type | Required | Description |
|---|---|---|---|
| varinatId | String | Yes | The unique ID of the variant of the product |
| Quantity | Number | Yes | The number of items of product added to cart |
| sellingPlanId | String | No | Unique ID incase of subscription enabled |
| attributes | Object | No | Custom Key Value Pairs to pass any additional info about the product |
Structure of Response
| Status | Response |
|---|---|
| Success | { "status": "success", "message": "Line items added to cart" } |
| Invalid Params | { "status": "error", "errorId": 400, "errorHandle": "invalid-params", "message": "Invalid params" } |
| Unexpected Error | { "status": "error", "errorId": 500, "errorHandle": "unknown-error", "message": "Something unexpected happened" } |
Example Usage
const product_data = VajroSDK.variables.product;
const variant_id= product_data.selectedVariant.id;
const quantity = 1;
const prod_metafield = product_data.metafields["product_height"];
const customAttributes = [
{ key: "product_height", value: prod_metafield },
{ key: "delivery_info", value: "Est. delivery 5 working days" }
];
function addItemToCartWithAttributes(variantId, quantity, customAttributes) {
VajroSDK.actions.addToCart([
{
variantId: variantId,
quantity: quantity,
attributes: customAttributes
}
])
.then(() => {
console.log("Item added to cart with attributes");
})
.catch(err => {
console.error("Error adding item to cart:", err);
});
}
function addToCart()
{
addItemToCartWithAttributes(variant_id, quantity, customAttributes);
}
Best Practices
- Use variantId when products have multiple options like size or color.
- Provide feedback to the user with showToast() or showAlert().
- Combine with the cartUpdated listener to refresh cart UI or item counts dynamically.
- Validate stock availability before adding to the cart (if using custom logic).
Caveats
- If the product requires variant selection, variantId must be specified.
- Does not open the cart automatically — use Vajro.actions.openCart() if needed.
- Adding out-of-stock items may fail silently; handle this with proper validation.
- The cartUpdated event is triggered asynchronously after the update.
Updated about 1 month ago