Skip to content

Commit

Permalink
flush when ready
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi committed Sep 11, 2021
1 parent 7d8768e commit 0e711e8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
4 changes: 2 additions & 2 deletions packages/next/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import PageLoader, { StyleSheetTuple } from './page-loader'
import measureWebVitals from './performance-relayer'
import { RouteAnnouncer } from './route-announcer'
import { createRouter, makePublicRouterInstance } from './router'
import { webVitalsCallbacks } from '../vitals/vitals'
import { flushWebVitalsCallbacks } from '../vitals/vitals'

/// <reference types="react-dom/experimental" />

Expand Down Expand Up @@ -310,7 +310,7 @@ export async function initNext(opts: { webpackHMR?: any } = {}) {
: 'web-vital',
}
exportedReportWebVitals?.(webVitals)
webVitalsCallbacks.forEach((callback) => callback(webVitals))
flushWebVitalsCallbacks(webVitals)
}

const pageEntrypoint =
Expand Down
20 changes: 13 additions & 7 deletions packages/next/vitals/vitals.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
import { useEffect, useState } from 'react'
import { useEffect } from 'react'
import { NextWebVitalsMetric } from '../pages/_app'

type ReportWebVitalsCallback = (webVitals: NextWebVitalsMetric) => any
export const webVitalsCallbacks = new Set<ReportWebVitalsCallback>()
const isClient = typeof window !== 'undefined'
let metric: NextWebVitalsMetric

export function useWebVitalsReport(callback: ReportWebVitalsCallback) {
// call on initial render, in a very early phase
useState(() => {
if (isClient) webVitalsCallbacks.add(callback)
})
export function flushWebVitalsCallbacks(_metric: NextWebVitalsMetric) {
metric = _metric
webVitalsCallbacks.forEach((callback) => callback(metric))
}

export function useWebVitalsReport(callback: ReportWebVitalsCallback) {
useEffect(() => {
if (metric) {
callback(metric)
return
}

webVitalsCallbacks.add(callback)
return () => {
webVitalsCallbacks.delete(callback)
}
Expand Down

0 comments on commit 0e711e8

Please sign in to comment.