All files / src/contexts/Analytics usePageView.ts

12.5% Statements 1/8
100% Branches 0/0
0% Functions 0/3
12.5% Lines 1/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36          1x                                                            
import { useCallback, useMemo } from "react";
import { useLocation } from "react-router-dom";
import { useAnalytics } from "./Analytics";
import type { PageViewOptions, PageViewConfig } from "./types";
 
export const usePageView = (opts: PageViewOptions) => {
  const { trackPageView } = useAnalytics();
  const { pathname } = useLocation();
 
  const options: PageViewConfig = useMemo(
    () => ({
      page: {
        // This is silly but the analytics library crashes in dev if using localhost as the pageURL :/
        pageURL: window.location.href.replace(
          "://localhost:3000",
          "://constructs.local.dev"
        ),
        ...opts.page,
      },
      event: {
        type: "pageview",
        name: opts.event.name,
        description: opts.event.description,
      },
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [pathname, opts]
  );
 
  const track = useCallback(() => {
    return trackPageView(options);
  }, [trackPageView, options]);
 
  return track;
};