Skip to content

Commit

Permalink
Merge pull request #255 from axiomhq/fix/web-vitals-duplicate-info
Browse files Browse the repository at this point in the history
fix: webVitals duplicate info
  • Loading branch information
dasfmi authored Dec 17, 2024
2 parents 0f45aec + 94426b8 commit 8926adf
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "next-axiom",
"description": "Send WebVitals from your Next.js project to Axiom.",
"version": "1.9.0",
"version": "1.9.1",
"author": "Axiom, Inc.",
"license": "MIT",
"contributors": [
Expand Down
33 changes: 30 additions & 3 deletions src/webVitals/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,37 @@
import { usePathname } from 'next/navigation';
import { useReportWebVitals as useNextReportWebVitals } from 'next/web-vitals';
import { reportWebVitalsWithPath } from './webVitals';
import { useCallback, useRef } from 'react';
export { type WebVitalsMetric } from './webVitals';
export { AxiomWebVitals } from './components'
export { AxiomWebVitals } from './components';

export function useReportWebVitals(path?: string) {
const pathName = usePathname();
useNextReportWebVitals((metric) => reportWebVitalsWithPath(metric, path || pathName));
const pathName = usePathname();

/**
* Refs allows us to stabilize the path name so that we can properly stabilize the reportWebVitalsFn
*/

const stabilizedPath = 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: Parameters<typeof useNextReportWebVitals>[0] = useCallback(
(metric) => reportWebVitalsWithPath(metric, stabilizedPath.current),
[]
);

useNextReportWebVitals(reportWebVitalsFn);
}

0 comments on commit 8926adf

Please sign in to comment.