Skip to main content

updateCartItemQty

Description

Updates the quantity of a cart item. This function supports both increasing and decreasing the quantity. If the quantity reaches zero during a decrease operation, the item is automatically removed from the cart. This is a hookable service that allows extensions to hook into the quantity update process.

Import

import { updateCartItemQty } from '@evershop/evershop/src/modules/checkout/services';

Usage

import { updateCartItemQty } from '@evershop/evershop/src/modules/checkout/services';

const updatedItem = await updateCartItemQty(cart, itemUuid, '2', 'increase', context);

Parameters

NameTypeDescription
cartCartThe cart object containing the item
uuidstringThe UUID of the item to update
qtystringThe quantity to increase or decrease by
action'increase' | 'decrease'The action to perform on the quantity
contextRecord<string, unknown>Context object for hookable functions (optional)

Return Value

Returns a Promise that resolves to the updated Item object.

Example

import { updateCartItemQty } from '@evershop/evershop/src/modules/checkout/services';

// Increase quantity by 1
async function increaseItemQty(cart, itemUuid) {
const updatedItem = await updateCartItemQty(
cart,
itemUuid,
'1',
'increase',
{ userId: 123 }
);

console.log('New quantity:', updatedItem.getData('qty'));
return updatedItem;
}

// Decrease quantity by 2
async function decreaseItemQty(cart, itemUuid) {
const updatedItem = await updateCartItemQty(
cart,
itemUuid,
'2',
'decrease',
{ userId: 123 }
);

console.log('New quantity:', updatedItem.getData('qty'));
return updatedItem;
}

Hooks

This function is hookable. Extensions can register hooks to execute before or after the quantity update:

import { hookBefore } from '@evershop/evershop/src/lib/util/hookable';
import { updateCartItemQty } from '@evershop/evershop/src/modules/checkout/services';

hookBefore(updateCartItemQty, async (cart, uuid, qty, action, context) => {
// Validate maximum quantity before update
const item = cart.getItem(uuid);
const maxQty = 10;

if (action === 'increase') {
const newQty = item.getData('qty') + parseInt(qty, 10);
if (newQty > maxQty) {
throw new Error(`Maximum quantity is ${maxQty}`);
}
}
});

See Also