onCartChange( )


Adds an event handler that runs when the cart changes.

The event handler set by the onCartChange() function runs when the cart changes.

The onCartChange() event handler is triggered when:

  • The cart is modified by native UI elements such as the 'Add to Cart' button, increase (+) and decrease (-) item quantity buttons, remove line item button (x), etc.
  • The refreshCart() function is called.

Important: Actions performed by Velo functions other than the refreshCart() function do not trigger the onCartChange() event handler.

Method Declaration
Copy
function onCartChange(handler: function): Promise<void>;
Method Parameters
handlerfunctionRequired

handler(): void The name of the function or the function expression to run when the cart is changed.

Add an event handler for cart changes
JavaScript
import { createClient } from "@wix/sdk"; import { site } from "@wix/site"; import { ecom } from "@wix/site-ecom"; import wixEcomBackend from "wix-ecom-backend"; const wixClient = createClient({ host: site.host(), modules: { ecom }, }); // handler function that gets the current cart on cart change const handler = async () => { // The wixEcomBackend.currentCart module is universal. // You can call its methods in frontend and backend code. try { const cart = await wixEcomBackend.currentCart.getCurrentCart(); let cartId = cart._id; console.log("cart ID: ", cartId); } catch (error) { console.error(error); // Handle the error } }; await wixClient.ecom.onCartChange(handler);
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?