Checkout utility functions
This topic provides details and instructions for using the utility functions available in the checkout drop-in component. These functions were moved from the integration layer and are now publicly accessible within the checkout block from @dropins/storefront-checkout/lib/utils.js
.
Quick imports
import { setAddressOnCart, estimateShippingCost, isVirtualCart, isEmptyCart, getCartShippingMethod, getCartAddress, getCartPaymentMethod, createFragment, createScopedSelector, validateForm, createMetaTag, setMetaTags, scrollToElement, transformAddressFormValuesToCartAddressInput, transformCartAddressToFormValues,} from '@dropins/storefront-checkout/lib/utils.js';
API Functions
setAddressOnCart
The setAddressOnCart
function creates a debounced handler for setting shipping or billing addresses on the cart, preventing excessive API calls when address data changes frequently.
export function setAddressOnCart({ type = 'shipping', debounceMs = 0, placeOrderBtn,}: { type?: 'shipping' | 'billing'; debounceMs?: number; placeOrderBtn?: RenderAPI;}): (change: AddressFormChange) => void;
Returns
Returns a function that accepts address form changes and updates the cart accordingly.
Usage
import { setAddressOnCart } from '@dropins/storefront-checkout/lib/utils.js';
// Set up debounced shipping address handlerconst handleShippingChange = setAddressOnCart({ type: 'shipping', debounceMs: 500, placeOrderBtn: placeOrderButtonAPI});
// Use with form change eventsshippingForm.addEventListener('input', (event) => { const formData = getFormValues(event.target.form); const isValid = validateForm(event.target.form);
handleShippingChange({ data: formData, isDataValid: isValid });});
estimateShippingCost
The estimateShippingCost
function creates a debounced handler for estimating shipping costs based on address information.
export function estimateShippingCost({ debounceMs = 0 }): (change: AddressFormChange) => void;
Returns
Returns a function that estimates shipping costs when address data changes.
Usage
import { estimateShippingCost } from '@dropins/storefront-checkout/lib/utils.js';
// Set up shipping cost estimationconst handleEstimateShipping = estimateShippingCost({ debounceMs: 300 });
// Use with address form changesaddressForm.addEventListener('input', (event) => { const formData = getFormValues(event.target.form); const isValid = validateForm(event.target.form);
handleEstimateShipping({ data: formData, isDataValid: isValid });});
Cart Data Functions
isVirtualCart
The isVirtualCart
function checks if a cart contains only virtual products (no shipping required). If no argument is provided, it reads the latest checkout data.
export function isVirtualCart(data?: Cart | null): boolean;
Returns
Returns true
if the cart is virtual, false
otherwise.
Usage
import { isVirtualCart } from '@dropins/storefront-checkout/lib/utils.js';
// Check if shipping is required using explicit dataconst cartData = await getCart();const skipShipping = isVirtualCart(cartData);
// Or check using the latest checkout dataconst skipShippingFromState = isVirtualCart();
if (skipShipping) { // Hide shipping-related UI document.querySelector('.shipping-section').style.display = 'none';}
isEmptyCart
The isEmptyCart
function checks if a cart is empty or null.
export function isEmptyCart(data: Cart | null): boolean;
Returns
Returns true
if the cart is empty or null, false
otherwise.
Usage
import { isEmptyCart } from '@dropins/storefront-checkout/lib/utils.js';
const cartData = await getCart();
if (isEmptyCart(cartData)) { // Show empty cart message showEmptyCartMessage(); return;}
// Proceed with checkoutproceedToCheckout(cartData);
getCartShippingMethod
The getCartShippingMethod
function retrieves the selected shipping method from cart data.
export function getCartShippingMethod(data: Cart | null): ShippingMethod | null;
Returns
Returns the selected shipping method object or null
if none is selected.
Usage
import { getCartShippingMethod } from '@dropins/storefront-checkout/lib/utils.js';
const cartData = await getCart();const shippingMethod = getCartShippingMethod(cartData);
if (shippingMethod) { console.log(`Shipping: ${shippingMethod.title} - $${shippingMethod.amount.value}`);}
getCartAddress
The getCartAddress
function retrieves shipping or billing address from cart data.
export function getCartAddress( data: Cart | null, type: 'shipping' | 'billing' = 'shipping'): Record<string, any> | null;
Returns
Returns the address object or null
if no address is set.
Usage
import { getCartAddress } from '@dropins/storefront-checkout/lib/utils.js';
const cartData = await getCart();const shippingAddress = getCartAddress(cartData, 'shipping');const billingAddress = getCartAddress(cartData, 'billing');
if (shippingAddress) { populateAddressForm(shippingAddress);}
getCartPaymentMethod
The getCartPaymentMethod
function retrieves the selected payment method from cart data.
export function getCartPaymentMethod(data: Cart | null): PaymentMethod | null;
Returns
Returns the selected payment method object or null
if none is selected.
Usage
import { getCartPaymentMethod } from '@dropins/storefront-checkout/lib/utils.js';
const cartData = await getCart();const paymentMethod = getCartPaymentMethod(cartData);
if (paymentMethod) { console.log(`Payment method: ${paymentMethod.code}`);}
DOM and Fragment Functions
createFragment
The createFragment
function creates a DocumentFragment
from an HTML string.
export function createFragment(html: string): DocumentFragment;
Returns
Returns a DocumentFragment containing the parsed HTML.
Usage
import { createFragment } from '@dropins/storefront-checkout/lib/utils.js';
const html = ` <div class="checkout-step"> <h2>Payment Information</h2> <form class="payment-form"> <!-- form fields --> </form> </div>`;
const fragment = createFragment(html);document.querySelector('.checkout-container').appendChild(fragment);
createScopedSelector
The createScopedSelector
function creates a scoped querySelector
function for a DocumentFragment.
export function createScopedSelector( fragment: DocumentFragment): (selector: string) => HTMLElement | null;
Returns
Returns a function that queries elements within the given fragment.
Usage
import { createFragment, createScopedSelector } from '@dropins/storefront-checkout/lib/utils.js';
const html = ` <div class="checkout-step"> <button class="next-btn">Next</button> <button class="prev-btn">Previous</button> </div>`;
const fragment = createFragment(html);const $ = createScopedSelector(fragment);
// Query within the fragment onlyconst nextButton = $('.next-btn');const prevButton = $('.prev-btn');
nextButton?.addEventListener('click', handleNext);
Form Functions
validateForm
The validateForm
function validates a form by name using form references.
export function validateForm( formName: string, formRef: RefObject<FormRef>): boolean;
Returns
Returns true
if the form is valid, false
otherwise.
Usage
import { validateForm } from '@dropins/storefront-checkout/lib/utils.js';
// Validate checkout form before submissionconst isShippingValid = validateForm('shipping-form', shippingFormRef);const isBillingValid = validateForm('billing-form', billingFormRef);
if (isShippingValid && isBillingValid) { proceedToPayment();} else { showValidationErrors();}
Meta Functions
createMetaTag
The createMetaTag
function creates or updates meta tags in the document head.
export function createMetaTag(property: string, content: string, type: string): void;
Returns
The function does not return a value; it modifies the document head.
Usage
import { createMetaTag } from '@dropins/storefront-checkout/lib/utils.js';
// Set checkout-specific meta tagscreateMetaTag('description', 'Complete your purchase securely', 'name');createMetaTag('og:title', 'Checkout - Your Store', 'property');
setMetaTags
The setMetaTags
function sets standard meta tags for a drop-in component.
export function setMetaTags(dropin: string): void;
Returns
The function does not return a value; it sets multiple meta tags.
Usage
import { setMetaTags } from '@dropins/storefront-checkout/lib/utils.js';
// Set meta tags for checkout pagesetMetaTags('Checkout');
Utility Functions
scrollToElement
The scrollToElement
function smoothly scrolls to and focuses on an HTML element.
export function scrollToElement(element: HTMLElement): void;
Returns
The function does not return a value; it performs scrolling and focusing.
Usage
import { scrollToElement } from '@dropins/storefront-checkout/lib/utils.js';
// Scroll to error fieldconst errorField = document.querySelector('.field-error');if (errorField) { scrollToElement(errorField);}
// Scroll to next checkout stepconst nextStep = document.querySelector('.checkout-step.active');scrollToElement(nextStep);
Data Transformer Functions
transformAddressFormValuesToCartAddressInput
The transformAddressFormValuesToCartAddressInput
function converts form data to cart address input format.
export const transformAddressFormValuesToCartAddressInput = ( data: Record<string, any>): ShippingAddressInput | BillingAddressInput;
Returns
Returns a formatted address input object for cart API calls.
Usage
import { transformAddressFormValuesToCartAddressInput } from '@dropins/storefront-checkout/lib/utils.js';
// Transform form data for APIconst formData = getFormValues(addressForm);const addressInput = transformAddressFormValuesToCartAddressInput(formData);
// Send to cart APIawait setShippingAddress(addressInput);
transformCartAddressToFormValues
The transformCartAddressToFormValues
function converts cart address data to the form values format.
export const transformCartAddressToFormValues = ( address: CartAddress): Record<string, any>;
Returns
Returns a form-compatible object with address data.
Usage
import { transformCartAddressToFormValues, getCartAddress } from '@dropins/storefront-checkout/lib/utils.js';
// Pre-populate form with existing addressconst cartData = await getCart();const shippingAddress = getCartAddress(cartData, 'shipping');
if (shippingAddress) { const formValues = transformCartAddressToFormValues(shippingAddress); populateForm(shippingForm, formValues);}
Common Usage Patterns
These utility functions work together to create robust checkout experiences:
Complete Address Handling
import { setAddressOnCart, transformAddressFormValuesToCartAddressInput, transformCartAddressToFormValues, getCartAddress, validateForm} from '@dropins/storefront-checkout/lib/utils.js';
// Set up address form handlingconst handleAddressChange = setAddressOnCart({ type: 'shipping', debounceMs: 500, placeOrderBtn: placeOrderAPI});
// Pre-populate form with existing dataconst cartData = await getCart();const existingAddress = getCartAddress(cartData, 'shipping');if (existingAddress) { const formValues = transformCartAddressToFormValues(existingAddress); populateAddressForm(formValues);}
// Handle form changesaddressForm.addEventListener('input', (event) => { const formData = getFormValues(event.target.form); const isValid = validateForm('shipping-address', formRef);
handleAddressChange({ data: formData, isDataValid: isValid });});
Cart State Management
import { isVirtualCart, isEmptyCart, getCartShippingMethod, getCartPaymentMethod} from '@dropins/storefront-checkout/lib/utils.js';
function updateCheckoutUI(cartData) { // Handle empty cart if (isEmptyCart(cartData)) { showEmptyCartMessage(); return; }
// Handle virtual cart (no shipping) if (isVirtualCart(cartData)) { hideShippingSection(); } else { const shippingMethod = getCartShippingMethod(cartData); updateShippingDisplay(shippingMethod); }
// Update payment display const paymentMethod = getCartPaymentMethod(cartData); updatePaymentDisplay(paymentMethod);}
Dynamic Content Creation
import { createFragment, createScopedSelector, scrollToElement} from '@dropins/storefront-checkout/lib/utils.js';
function createCheckoutStep(stepHtml, stepName) { const fragment = createFragment(stepHtml); const $ = createScopedSelector(fragment);
// Set up step-specific interactions const nextButton = $('.next-step'); const prevButton = $('.prev-step');
nextButton?.addEventListener('click', () => { if (validateCurrentStep()) { proceedToNextStep(); } else { const errorField = $('.field-error'); if (errorField) scrollToElement(errorField); } });
return fragment;}