简体   繁体   中英

How can I display web vitals metrics into my page footer with nextjs and react hook?

Hi I'm just a newbie on next.js and react. I just find that next.js has a built-in function that can log performance metrics(eg fcp) into console that I would like to display it in my Metric componenthttps://nextjs.org/docs/advanced-features/measuring-performance

This is my Metric component:

export let fcpTime = 0;

const Metric = () => {
   // display metrics
   useEffect(() => {
       console.log("fcpTime: ", fcpTime); // fcpTime still = 0
   }, []);
}

export default Metric;

I tried to set fcpTime inside the case 'FCP':

// pages/_app.js
export function reportWebVitals(metric) {
  switch (metric.name) {
    case 'FCP':
      // handle FCP results
      fcpTime = metric.value;
      break
    case 'LCP':
      // handle LCP results
      break
    case 'CLS':
      // handle CLS results
      break
    case 'FID':
      // handle FID results
      break
    case 'TTFB':
      // handle TTFB results
      break
    default:
      break
  }
}

However, how can I can pass the FCP result to my component and make it re-render again when FCP result is logged? Thank you.

At the end I dispatch a new CustomEvent and useEffect to addEventListener into this custom event. Here is the code:

_app.js

export function reportWebVitals(result) {
  if (result.name === "FCP") {
    dispatchFcpEvent(result);
  }
};

Metric.js

let fcpEvent = null;

export const dispatchFcpEvent = (fcp) => {
  fcpEvent = new CustomEvent('fcpTime', { detail: fcp.value });
  window.dispatchEvent(fcpEvent);
}

const Copyright = () => {
  const [fcpTime, setFcpTime] = useState();

  if (typeof window !== "undefined") {
    const onFcpTimeUpdate = (e) => {
      setFcpTime(e.detail);
      window.removeEventListener('fcpTime', onFcpTimeUpdate, false);
    };
    useEffect(() => {
      window.addEventListener('fcpTime', onFcpTimeUpdate);
    }, []);
  }

  // return below
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM