Skip to main content

How to listen to cart changes and modify cart

Introduction

This guide will help you to listen to cart changes and modify cart. You can listen to cart changes using the manage-cart-after-response hook. You can use this hook to add/edit/remove products from cart.

Hooks

There is two hooks available to listen to cart changes.

Hook Name: manage-cart-before-update

This hook is called before the cart is updated.

Input Parameters:

ParameterDescriptionExample
currentCartCurrent cart object. This is the cart object before the update. Null if the cart is empty or if cart is not created yet.https://shopify.dev/docs/api/storefront/2023-01/objects/checkout
lineItemsToAddLine items to be added to cart. This is the line items that will be added to cart.[{"variantId":"123",quantity: 1, "customAttributes": [{key: 'sampl_1',value: '123'}}]
lineItemsToUpdateLine items to be updated in cart. This is the line items that will be updated in cart.[{"id":"lineItemIt",quantity: 1, "customAttributes": [{key: 'sampl_1',value: '123'}}]
lineItemsToRemoveLine item ids to be removed from cart. This is the line items that will be removed from cart.["123"]

Hook Name: manage-cart-after-response

This hook is called after the cart is updated.

Input Parameters:

ParameterDescriptionExample
currentCartCurrent cart object. This is the cart object after the update.https://shopify.dev/docs/api/storefront/2023-01/objects/checkout
lineItemsToAddLine items to be added to cart. This is the line items that will be added to cart.[{"variantId":"123",quantity: 1, "customAttributes": [{key: 'sampl_1',value: '123'}}]
lineItemsToUpdateLine items to be updated in cart. This is the line items that will be updated in cart.[{"id":"lineItemIt",quantity: 1, "customAttributes": [{key: 'sampl_1',value: '123'}}]
lineItemsToRemoveLine item ids to be removed from cart. This is the line items that will be removed from cart.["123"]

Usage

Let set max quantity of a product to 5. If the quantity is more than 5, we will set the quantity to 5.

import { appmakerFunctions } from '@appmaker-xyz/core';
appmakerFunctions.registerAppmakerFn({
trigger: 'manage-cart-before-update',
functionName: 'modify-cart',
fn: (input) => {
input?.lineItemsToAdd?.forEach((lineItem) => {
if (lineItem.quantity > 5) {
lineItem.quantity = 5;
}
});
input?.lineItemsToUpdate?.forEach((lineItem) => {
if (lineItem.quantity > 5) {
lineItem.quantity = 5;
}
});
return input;
},
});