@logtail/next
Version:
Better Stack Telemetry Next.js client
34 lines • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useReportWebVitals = exports.BetterStackWebVitals = void 0;
const navigation_1 = require("next/navigation");
const web_vitals_1 = require("next/web-vitals");
const webVitals_1 = require("./webVitals");
const react_1 = require("react");
var components_1 = require("./components");
Object.defineProperty(exports, "BetterStackWebVitals", { enumerable: true, get: function () { return components_1.BetterStackWebVitals; } });
function useReportWebVitals(path) {
const pathName = (0, navigation_1.usePathname)();
/**
* Refs allows us to stabilize the path name so that we can properly stabilize the reportWebVitalsFn
*/
const stabilizedPath = (0, react_1.useRef)(path || pathName);
/**
* If the path changes, we update the stabilizedPath ref
*/
if (typeof path === 'string' && path !== stabilizedPath.current) {
stabilizedPath.current = pathName;
}
else if (typeof path === 'string' && path === stabilizedPath.current) {
stabilizedPath.current = path;
}
/**
* Stabilizing the reportWebVitalsFn avoids reporting the same metrics from multiple paths, it happens because internally
* the useReportWebVitals from next uses a useEffect to report the metrics, and the reportWebVitalsFn is passed as a dependency
* to the useEffect, so when the path changes, the useEffect is re-run, and the same metrics are reported again.
*/
const reportWebVitalsFn = (0, react_1.useCallback)((metric) => (0, webVitals_1.reportWebVitalsWithPath)(metric, stabilizedPath.current), []);
(0, web_vitals_1.useReportWebVitals)(reportWebVitalsFn);
}
exports.useReportWebVitals = useReportWebVitals;
//# sourceMappingURL=index.js.map