useGtm

Push Google Tag Manager ecommerce events (product views, add to cart, purchase) to the data layer.

Use useGtm when your theme must report customer actions, such as viewing a product or adding it to the cart, to the merchant's Google Tag Manager container.

Example

app/components/product/AddToCart.tsx
import { useEffect } from 'react';
import { useGtm } from '@salla.sa/twilight-theme-engine/hooks/useGtm';
import type { Product } from '@salla.sa/twilight-theme-engine/types';

export function AddToCart({ product }: { product: Product }) {
  const gtm = useGtm();

  useEffect(() => {
    gtm.detail(product);
  }, [product.id]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <button
      onClick={async () => {
        await window.salla?.cart.addItem(product.id, 1);
        gtm.add(product, 1);
      }}
    >
      Add to cart
    </button>
  );
}

API

function useGtm(): UseGtmResult;
PropTypeDescription
enabledbooleantrue when the store has at least one id in settings.keys.gtm.
push(data: Record<string, unknown>) => voidPushes any object to window.dataLayer.
viewPage(pageType: string) => voidPushes { event: 'viewPage', pageType }.
detail(product: Product) => voidProduct page view. Event detail.
impressions(products: Product[], list?: string) => voidProducts shown in a listing, with positions starting at 1. Event impressions. Does nothing for an empty list.
click(product: Product, list?: string, position?: number) => voidProduct clicked in a listing. Event click.
add(product: Product, quantity?: number) => voidAdded to the cart. Event addToCart. Quantity defaults to 1.
remove(item: CartItem) => voidRemoved from the cart. Event removeFromCart.
checkout(cart: Cart, step?: number) => voidCheckout started. Event checkout. Step defaults to 1.
purchase(orderId: string | number, cart: Cart) => voidOrder placed. Event purchase, with revenue, tax and coupon from the cart.

Ecommerce events carry an ecommerce object with currencyCode, a unique event_id, and the products (id, name, price, brand, category, quantity). Product price is sale_price.

Gotchas

  • Everything is a no-op when the store has no Tag Manager id, so you can call the methods without checking enabled.
  • The engine loads the Tag Manager script itself. This hook only pushes events to window.dataLayer.
  • Call the methods from effects and event handlers, not during render. They use window, so they only work in the browser.
  • The currency of detail, impressions, click and add is the product's own currency. For remove, checkout and purchase it is the signed-in customer's preferred currency, and SAR for guests.
  • The hook calls useUser inside, so the result is a new object on every render. Do not use gtm as a useEffect dependency; keep it in a ref, as in the page views recipe.
  • The engine does not call these methods for you. Your components decide where each event is sent.

Next

On this page