-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #255 from axiomhq/fix/web-vitals-duplicate-info
fix: webVitals duplicate info
- Loading branch information
Showing
3 changed files
with
33 additions
and
6 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |