@zendesk/react-measure-timing-hooks
Version:
react hooks for measuring time to interactive and time to render of components
45 lines • 2.19 kB
JavaScript
/**
* Copyright Zendesk, Inc.
*
* Use of this source code is governed under the Apache License, Version 2.0
* found at http://www.apache.org/licenses/LICENSE-2.0.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReactMeasureErrorBoundary = exports.useOnComponentUnmount = exports.useOnErrorBoundaryDidCatch = void 0;
const react_1 = require("react");
let errorMetadataCurrentlyBeingThrown;
const useOnErrorBoundaryDidCatch = (onCaughtError) => {
(0, react_1.useEffect)(() => () => {
if (!errorMetadataCurrentlyBeingThrown)
return;
// this will only run if React decides to unmount the tree that threw the error
onCaughtError(errorMetadataCurrentlyBeingThrown);
}, [onCaughtError]);
};
exports.useOnErrorBoundaryDidCatch = useOnErrorBoundaryDidCatch;
const useOnComponentUnmount = (onComponentUnmountCallback, dependencies = []) => {
const onComponentUnmountRef = (0, react_1.useRef)(onComponentUnmountCallback);
onComponentUnmountRef.current = onComponentUnmountCallback;
(0, react_1.useEffect)(() => () => {
onComponentUnmountRef.current(errorMetadataCurrentlyBeingThrown);
}, dependencies);
};
exports.useOnComponentUnmount = useOnComponentUnmount;
class ReactMeasureErrorBoundary extends react_1.Component {
componentDidCatch(error, errorInfo) {
// since 'componentDidCatch' runs synchronously right before useEffect clean-up functions
// belonging to the component that has thrown,
// that means this metadata is available within that synchronous frame to the component
// this should work even in concurrent mode;
// at least for the purpose of reporting metadata, or metrics such as counts, this is good enough
errorMetadataCurrentlyBeingThrown = { error, errorInfo };
setTimeout(() => {
// we want this data to be available synchronously - only in the same JS frame
// so we clean-up immediately after:
errorMetadataCurrentlyBeingThrown = undefined;
});
}
}
exports.ReactMeasureErrorBoundary = ReactMeasureErrorBoundary;
//# sourceMappingURL=ErrorBoundary.js.map
;