addCartItem
Description
Adds an item to the cart. If an item with the same SKU already exists in the cart, the quantities are merged instead of creating a duplicate item. This is a hookable service that allows extensions to hook into the add-to-cart process.
Import
import { addCartItem } from '@evershop/evershop/src/modules/checkout/services';
Usage
import { addCartItem } from '@evershop/evershop/src/modules/checkout/services';
const addedItem = await addCartItem(cart, productId, 2, context);
Parameters
| Name | Type | Description |
|---|---|---|
cart | Cart | The cart object to which the item will be added |
productID | number | The ID of the product to add |
qty | number | string | The quantity of the product to add |
context | Record<string, unknown> | Context object for hookable functions (optional) |
Return Value
Returns a Promise that resolves to the added or updated Item object.
Example
import { addCartItem } from '@evershop/evershop/src/modules/checkout/services';
async function addProductToCart(cart, productId, quantity) {
try {
const item = await addCartItem(cart, productId, quantity, {
userId: 123,
sessionId: 'abc123'
});
console.log('Added item:', item.getData('product_name'));
console.log('Total quantity:', item.getData('qty'));
return item;
} catch (error) {
console.error('Failed to add item:', error.message);
throw error;
}
}
Hooks
This function is hookable. Extensions can register hooks to execute before or after adding items:
import { hookAfter } from '@evershop/evershop/src/lib/util/hookable';
import { addCartItem } from '@evershop/evershop/src/modules/checkout/services';
hookAfter(addCartItem, async (addedItem, cart, productID, qty, context) => {
// Track add-to-cart event for analytics
await trackAddToCart({
productId: productID,
quantity: qty,
cartId: cart.getId(),
userId: context.userId
});
return addedItem;
});
See Also
- removeCartItem - Remove an item from the cart
- updateCartItemQty - Update cart item quantity
- saveCart - Save cart changes to the database