xtablo-source/apps/main/src/hooks/useDatadogRumViewName.tsx
2025-10-30 18:23:24 +01:00

38 lines
1.1 KiB
TypeScript

import { datadogRum } from "@datadog/browser-rum";
import { useEffect } from "react";
import { matchRoutes, RouteMatch, useLocation } from "react-router-dom";
import { routes } from "../lib/routes";
function computeViewName(routeMatches: RouteMatch[]) {
let viewName = "";
for (let index = 0; index < routeMatches.length; index++) {
const routeMatch = routeMatches[index];
const path = routeMatch.route.path;
// Skip pathless routes
if (!path) {
continue;
}
if (path.startsWith("/")) {
// Handle absolute child route paths
viewName = path;
} else {
// Handle route paths ending with "/"
viewName += viewName.endsWith("/") ? path : `/${path}`;
}
}
return viewName || "/";
}
export const useDatadogRumViewName = () => {
const location = useLocation();
useEffect(() => {
const routeMatches = matchRoutes(routes, location.pathname);
const viewName = routeMatches && computeViewName(routeMatches);
if (viewName) {
datadogRum.startView({ name: viewName });
}
}, [location.pathname]);
};