services/tracking/useTracking.jsjavascript
import { useCallback, useLayoutEffect, useRef } from "react";
import { useLocation } from "react-router";
import { useAnalytics } from "@tracking/messe-tracking/react";
import { areaForPath } from "./area";
/**
* useAnalytics() of the messe-tracking SDK, but every `trackEvent` carries
* `payload.area` (see area.js) - use it instead of useAnalytics() in components.
*
* The SDK's `context` option (index.jsx) already adds the area of the URL at
* call time to every event; this wrapper's explicit area takes precedence and
* is taken from the route the component last rendered with instead, so an
* event sent while leaving (ppt_close on
* unmount, after the URL already switched to another app) still belongs to
* the app it happened in. `trackEvent` keeps its identity across renders, so
* it stays safe in effect dependency arrays.
*
* @returns {{ trackEvent: Function, trackSlideOrStory: Function }}
*/
export const useTracking = () => {
const analytics = useAnalytics();
const { pathname } = useLocation();
const areaRef = useRef(areaForPath(pathname));
// a layout effect runs before every passive effect, so effects that track
// (slide_view, ...) already see the new area
useLayoutEffect(() => {
areaRef.current = areaForPath(pathname);
}, [pathname]);
const trackEvent = useCallback(
(eventType, { payload, ...rest } = {}) =>
analytics?.trackEvent?.(eventType, {
...rest,
payload: { area: areaRef.current, ...payload },
}),
[analytics]
);
const trackSlideOrStory = useCallback(
(storyId, slideIndex, extra) =>
analytics?.trackSlideOrStory?.(storyId, slideIndex, { area: areaRef.current, ...extra }),
[analytics]
);
return { trackEvent, trackSlideOrStory };
};