Launch Week Day 5: Introducing Reachability for PHP.Learn More
Socket
Book a DemoSign in
Socket

react-error-boundary

Package Overview
Dependencies
Maintainers
2
Versions
57
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-error-boundary - npm Package Compare versions

Comparing version
3.1.4
to
4.0.0
+65
dist/react-error-boundary.d.ts
import { Component, ComponentType, FunctionComponent, ReactElement, ReactNode, ErrorInfo, PropsWithChildren, PropsWithRef } from "react";
export type ErrorBoundaryContextType = {
didCatch: false;
error: any;
resetErrorBoundary: (...args: any[]) => void;
};
export const ErrorBoundaryContext: import("react").Context<ErrorBoundaryContextType | null>;
declare function FallbackRender(props: FallbackProps): ReactNode;
export type FallbackProps = {
error: any;
resetErrorBoundary: (...args: any[]) => void;
};
type ErrorBoundarySharedProps = {
onError?: (error: Error, info: {
componentStack: string;
}) => void;
onReset?: (details: {
reason: "imperative-api";
args: any[];
} | {
reason: "keys";
prev: any[] | undefined;
next: any[] | undefined;
}) => void;
resetKeys?: any[];
};
export type ErrorBoundaryPropsWithComponent = ErrorBoundarySharedProps & {
fallback?: never;
FallbackComponent: ComponentType<FallbackProps>;
fallbackRender?: never;
};
export type ErrorBoundaryPropsWithRender = ErrorBoundarySharedProps & {
fallback?: never;
FallbackComponent?: never;
fallbackRender: typeof FallbackRender;
};
export type ErrorBoundaryPropsWithFallback = ErrorBoundarySharedProps & {
fallback: ReactElement<unknown, string | FunctionComponent | typeof Component> | null;
FallbackComponent?: never;
fallbackRender?: never;
};
export type ErrorBoundaryProps = ErrorBoundaryPropsWithFallback | ErrorBoundaryPropsWithComponent | ErrorBoundaryPropsWithRender;
type ErrorBoundaryState = {
didCatch: boolean;
error: any;
};
export class ErrorBoundary extends Component<PropsWithRef<PropsWithChildren<ErrorBoundaryProps>>, ErrorBoundaryState> {
state: ErrorBoundaryState;
static getDerivedStateFromError(error: Error): {
didCatch: boolean;
error: Error;
};
resetErrorBoundary: (...args: any[]) => void;
componentDidCatch(error: Error, info: ErrorInfo): void;
componentDidUpdate(prevProps: ErrorBoundaryProps, prevState: ErrorBoundaryState): void;
render(): string | number | boolean | import("react").ReactElement<any, string | import("react").JSXElementConstructor<any>> | import("react").ReactFragment | import("react").FunctionComponentElement<import("react").ProviderProps<ErrorBoundaryContextType | null>> | null | undefined;
}
export type UseErrorBoundaryApi<Error> = {
resetBoundary: () => void;
showBoundary: (error: Error) => void;
};
export function useErrorBoundary<Error = any>(): UseErrorBoundaryApi<Error>;
export function withErrorBoundary<Props extends Object>(Component: ComponentType<Props>, errorBoundaryProps: ErrorBoundaryProps): ComponentType<Props>;
//# sourceMappingURL=react-error-boundary.d.ts.map
{"mappings":";AAEA,uCAAuC;IACrC,QAAQ,EAAE,KAAK,CAAC;IAChB,KAAK,EAAE,GAAG,CAAC;IACX,kBAAkB,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;CAC9C,CAAC;AAEF,OAAO,MAAM,8EACyC,CAAC;ACDvD,gCAAgC,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC;AAEjE,4BAA4B;IAC1B,KAAK,EAAE,GAAG,CAAC;IACX,kBAAkB,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;CAC9C,CAAC;AAEF,gCAAgC;IAC9B,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;IACnE,OAAO,CAAC,EAAE,CACR,OAAO,EACH;QAAE,MAAM,EAAE,gBAAgB,CAAC;QAAC,IAAI,EAAE,GAAG,EAAE,CAAA;KAAE,GACzC;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,GAAG,EAAE,GAAG,SAAS,CAAC;QAAC,IAAI,EAAE,GAAG,EAAE,GAAG,SAAS,CAAA;KAAE,KACrE,IAAI,CAAC;IACV,SAAS,CAAC,EAAE,GA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KAAK,CAAC,CAiC1E;ACtCD,kCAAkC,KAAK,SAAS,MAAM,EACpD,SAAS,EAAE,cAAc,KAAK,CAAC,EAC/B,kBAAkB,EAAE,kBAAkB,GACrC,cAAc,KAAK,CAAC,CActB","sources":["src/src/ErrorBoundaryContext.ts","src/src/types.ts","src/src/ErrorBoundary.ts","src/src/assertErrorBoundaryContext.ts","src/src/useErrorBoundary.ts","src/src/withErrorBoundary.ts","src/src/index.ts","src/index.ts"],"sourcesContent":[null,null,null,null,null,null,null,"export * from \"./ErrorBoundary\";\nexport * from \"./ErrorBoundaryContext\";\nexport * from \"./useErrorBoundary\";\nexport * from \"./withErrorBoundary\";\n\n// TypeScript types\nexport * from \"./types\";\n"],"names":[],"version":3,"file":"react-error-boundary.d.ts.map"}
var $8zHUo$react = require("react");
function $parcel$exportWildcard(dest, source) {
Object.keys(source).forEach(function(key) {
if (key === 'default' || key === '__esModule' || dest.hasOwnProperty(key)) {
return;
}
Object.defineProperty(dest, key, {
enumerable: true,
get: function get() {
return source[key];
}
});
});
return dest;
}
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
var $6d6d4999e62b3ee0$exports = {};
$parcel$export($6d6d4999e62b3ee0$exports, "ErrorBoundary", () => $6d6d4999e62b3ee0$export$e926676385687eaf);
var $4a61716688322eb0$exports = {};
$parcel$export($4a61716688322eb0$exports, "ErrorBoundaryContext", () => $4a61716688322eb0$export$b16d9fb1a22de840);
const $4a61716688322eb0$export$b16d9fb1a22de840 = (0, $8zHUo$react.createContext)(null);
const $6d6d4999e62b3ee0$var$initialState = {
didCatch: false,
error: null
};
class $6d6d4999e62b3ee0$export$e926676385687eaf extends (0, $8zHUo$react.Component) {
state = $6d6d4999e62b3ee0$var$initialState;
static getDerivedStateFromError(error) {
return {
didCatch: true,
error: error
};
}
resetErrorBoundary = (...args)=>{
const { error: error } = this.state;
if (error !== null) {
this.props.onReset?.({
args: args,
reason: "imperative-api"
});
this.setState($6d6d4999e62b3ee0$var$initialState);
}
};
componentDidCatch(error, info) {
this.props.onError?.(error, info);
}
componentDidUpdate(prevProps, prevState) {
const { didCatch: didCatch } = this.state;
const { resetKeys: resetKeys } = this.props;
// There's an edge case where if the thing that triggered the error happens to *also* be in the resetKeys array,
// we'd end up resetting the error boundary immediately.
// This would likely trigger a second error to be thrown.
// So we make sure that we don't check the resetKeys on the first call of cDU after the error is set.
if (didCatch && prevState.error !== null && $6d6d4999e62b3ee0$var$hasArrayChanged(prevProps.resetKeys, resetKeys)) {
this.props.onReset?.({
next: resetKeys,
prev: prevProps.resetKeys,
reason: "keys"
});
this.setState($6d6d4999e62b3ee0$var$initialState);
}
}
render() {
const { children: children , fallbackRender: fallbackRender , FallbackComponent: FallbackComponent , fallback: fallback } = this.props;
const { didCatch: didCatch , error: error } = this.state;
if (didCatch) {
const props = {
error: error,
resetErrorBoundary: this.resetErrorBoundary
};
if ((0, $8zHUo$react.isValidElement)(fallback)) return fallback;
else if (typeof fallbackRender === "function") return fallbackRender(props);
else if (FallbackComponent) return (0, $8zHUo$react.createElement)(FallbackComponent, props);
else throw new Error("react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop");
}
return (0, $8zHUo$react.createElement)((0, $4a61716688322eb0$export$b16d9fb1a22de840).Provider, {
value: {
didCatch: didCatch,
error: error,
resetErrorBoundary: this.resetErrorBoundary
}
}, children);
}
}
function $6d6d4999e62b3ee0$var$hasArrayChanged(a = [], b = []) {
return a.length !== b.length || a.some((item, index)=>!Object.is(item, b[index]));
}
var $3c4937b727a6fcfb$exports = {};
$parcel$export($3c4937b727a6fcfb$exports, "useErrorBoundary", () => $3c4937b727a6fcfb$export$c052f6604b7d51fe);
function $f8678e3a8e88e8a4$export$f20aa86254872370(value) {
if (value == null || typeof value.didCatch !== "boolean" || typeof value.resetErrorBoundary !== "function") throw new Error("ErrorBoundaryContext not found");
return true;
}
function $3c4937b727a6fcfb$export$c052f6604b7d51fe() {
const context = (0, $8zHUo$react.useContext)((0, $4a61716688322eb0$export$b16d9fb1a22de840));
(0, $f8678e3a8e88e8a4$export$f20aa86254872370)(context);
const [state, setState] = (0, $8zHUo$react.useState)({
error: null,
hasError: false
});
const memoized = (0, $8zHUo$react.useMemo)(()=>({
resetBoundary: ()=>{
context?.resetErrorBoundary();
setState({
error: null,
hasError: false
});
},
showBoundary: (error)=>setState({
error: error,
hasError: true
})
}), [
context?.resetErrorBoundary
]);
if (state.hasError) throw state.error;
return memoized;
}
var $9e88dd86e0bb2944$exports = {};
$parcel$export($9e88dd86e0bb2944$exports, "withErrorBoundary", () => $9e88dd86e0bb2944$export$f0c7a449e0cfaec7);
function $9e88dd86e0bb2944$export$f0c7a449e0cfaec7(Component, errorBoundaryProps) {
const Wrapped = (props)=>{
return (0, $8zHUo$react.createElement)((0, $6d6d4999e62b3ee0$export$e926676385687eaf), errorBoundaryProps, (0, $8zHUo$react.createElement)(Component, props));
};
// Format for display in DevTools
const name = Component.displayName || Component.name || "Unknown";
Wrapped.displayName = `withErrorBoundary(${name})`;
return Wrapped;
}
var $faefaad95e5fcca0$exports = {};
$parcel$exportWildcard(module.exports, $6d6d4999e62b3ee0$exports);
$parcel$exportWildcard(module.exports, $4a61716688322eb0$exports);
$parcel$exportWildcard(module.exports, $3c4937b727a6fcfb$exports);
$parcel$exportWildcard(module.exports, $9e88dd86e0bb2944$exports);
$parcel$exportWildcard(module.exports, $faefaad95e5fcca0$exports);
//# sourceMappingURL=react-error-boundary.js.map
{"mappings":";;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;ACAA;AAQO,MAAM,4CACX,CAAA,GAAA,0BAAY,EAAmC,IAAI;;;ADOrD,MAAM,qCAAmC;IACvC,UAAU,KAAK;IACf,OAAO,IAAI;AACb;AAEO,MAAM,kDAAsB,CAAA,GAAA,sBAAS,AAAD;IAIzC,QAAQ,mCAAa;IAErB,OAAO,yBAAyB,KAAY,EAAE;QAC5C,OAAO;YAAE,UAAU,IAAI;mBAAE;QAAM;IACjC;I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CAAA,GAAA,0BAAa,AAAD,EACjB,CAAA,GAAA,yCAAa,AAAD,GACZ,oBACA,CAAA,GAAA,0BAAY,EAAE,WAAW;IAE7B;IAEA,iCAAiC;IACjC,MAAM,OAAO,UAAU,WAAW,IAAI,UAAU,IAAI,IAAI;IACxD,QAAQ,WAAW,GAAG,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;IAElD,OAAO;AACT;;;;;","sources":["src/index.ts","src/ErrorBoundary.ts","src/ErrorBoundaryContext.ts","src/useErrorBoundary.ts","src/assertErrorBoundaryContext.ts","src/withErrorBoundary.ts","src/types.ts"],"sourcesContent":["export * from \"./ErrorBoundary\";\nexport * from \"./ErrorBoundaryContext\";\nexport * from \"./useErrorBoundary\";\nexport * from \"./withErrorBoundary\";\n\n// TypeScript types\nexport * from \"./types\";\n","import {\n Component,\n createElement,\n ErrorInfo,\n isValidElement,\n PropsWithChildren,\n PropsWithRef,\n} from \"react\";\nimport {\n ErrorBoundaryContextType,\n ErrorBoundaryContext,\n} from \"./ErrorBoundaryContext\";\nimport { ErrorBoundaryProps, FallbackProps } from \"./types\";\n\ntype ErrorBoundaryState = { didCatch: boolean; error: any };\n\nconst initialState: ErrorBoundaryState = {\n didCatch: false,\n error: null,\n};\n\nexport class ErrorBoundary extends Component<\n PropsWithRef<PropsWithChildren<ErrorBoundaryProps>>,\n ErrorBoundaryState\n> {\n state = initialState;\n\n static getDerivedStateFromError(error: Error) {\n return { didCatch: true, error };\n }\n\n resetErrorBoundary = (...args: any[]) => {\n const { error } = this.state;\n\n if (error !== null) {\n this.props.onReset?.({\n args,\n reason: \"imperative-api\",\n });\n\n this.setState(initialState);\n }\n };\n\n componentDidCatch(error: Error, info: ErrorInfo) {\n this.props.onError?.(error, info);\n }\n\n componentDidUpdate(\n prevProps: ErrorBoundaryProps,\n prevState: ErrorBoundaryState\n ) {\n const { didCatch } = this.state;\n const { resetKeys } = this.props;\n\n // There's an edge case where if the thing that triggered the error happens to *also* be in the resetKeys array,\n // we'd end up resetting the error boundary immediately.\n // This would likely trigger a second error to be thrown.\n // So we make sure that we don't check the resetKeys on the first call of cDU after the error is set.\n\n if (\n didCatch &&\n prevState.error !== null &&\n hasArrayChanged(prevProps.resetKeys, resetKeys)\n ) {\n this.props.onReset?.({\n next: resetKeys,\n prev: prevProps.resetKeys,\n reason: \"keys\",\n });\n\n this.setState(initialState);\n }\n }\n\n render() {\n const { children, fallbackRender, FallbackComponent, fallback } =\n this.props;\n const { didCatch, error } = this.state;\n\n if (didCatch) {\n const props: FallbackProps = {\n error,\n resetErrorBoundary: this.resetErrorBoundary,\n };\n\n if (isValidElement(fallback)) {\n return fallback;\n } else if (typeof fallbackRender === \"function\") {\n return fallbackRender(props);\n } else if (FallbackComponent) {\n return createElement(FallbackComponent, props);\n } else {\n throw new Error(\n \"react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop\"\n );\n }\n }\n\n return createElement(\n ErrorBoundaryContext.Provider,\n {\n value: {\n didCatch,\n error,\n resetErrorBoundary: this.resetErrorBoundary,\n },\n },\n children\n );\n }\n}\n\nfunction hasArrayChanged(a: any[] = [], b: any[] = []) {\n return (\n a.length !== b.length || a.some((item, index) => !Object.is(item, b[index]))\n );\n}\n","import { createContext } from \"react\";\n\nexport type ErrorBoundaryContextType = {\n didCatch: false;\n error: any;\n resetErrorBoundary: (...args: any[]) => void;\n};\n\nexport const ErrorBoundaryContext =\n createContext<ErrorBoundaryContextType | null>(null);\n","import { useContext, useMemo, useState } from \"react\";\nimport { assertErrorBoundaryContext } from \"./assertErrorBoundaryContext\";\nimport { ErrorBoundaryContext } from \"./ErrorBoundaryContext\";\n\nexport type UseErrorBoundaryApi<Error> = {\n resetBoundary: () => void;\n showBoundary: (error: Error) => void;\n};\n\nexport function useErrorBoundary<Error = any>(): UseErrorBoundaryApi<Error> {\n const context = useContext(ErrorBoundaryContext);\n\n assertErrorBoundaryContext(context);\n\n const [state, setState] = useState<{\n error: Error | null;\n hasError: boolean;\n }>({\n error: null,\n hasError: false,\n });\n\n const memoized = useMemo(\n () => ({\n resetBoundary: () => {\n context?.resetErrorBoundary();\n setState({ error: null, hasError: false });\n },\n showBoundary: (error: Error) =>\n setState({\n error,\n hasError: true,\n }),\n }),\n [context?.resetErrorBoundary]\n );\n\n if (state.hasError) {\n throw state.error;\n }\n\n return memoized;\n}\n","import { ErrorBoundaryContextType } from \"./ErrorBoundaryContext\";\n\nexport function assertErrorBoundaryContext(\n value: any\n): value is ErrorBoundaryContextType {\n if (\n value == null ||\n typeof value.didCatch !== \"boolean\" ||\n typeof value.resetErrorBoundary !== \"function\"\n ) {\n throw new Error(\"ErrorBoundaryContext not found\");\n }\n\n return true;\n}\n","import { ComponentType, createElement } from \"react\";\nimport { ErrorBoundary } from \"./ErrorBoundary\";\nimport { ErrorBoundaryProps } from \"./types\";\n\nexport function withErrorBoundary<Props extends Object>(\n Component: ComponentType<Props>,\n errorBoundaryProps: ErrorBoundaryProps\n): ComponentType<Props> {\n const Wrapped: ComponentType<Props> = (props: Props) => {\n return createElement(\n ErrorBoundary,\n errorBoundaryProps,\n createElement(Component, props)\n );\n };\n\n // Format for display in DevTools\n const name = Component.displayName || Component.name || \"Unknown\";\n Wrapped.displayName = `withErrorBoundary(${name})`;\n\n return Wrapped;\n}\n","import {\n Component,\n ComponentType,\n FunctionComponent,\n ReactElement,\n ReactNode,\n} from \"react\";\n\ndeclare function FallbackRender(props: FallbackProps): ReactNode;\n\nexport type FallbackProps = {\n error: any;\n resetErrorBoundary: (...args: any[]) => void;\n};\n\ntype ErrorBoundarySharedProps = {\n onError?: (error: Error, info: { componentStack: string }) => void;\n onReset?: (\n details:\n | { reason: \"imperative-api\"; args: any[] }\n | { reason: \"keys\"; prev: any[] | undefined; next: any[] | undefined }\n ) => void;\n resetKeys?: any[];\n};\n\nexport type ErrorBoundaryPropsWithComponent = ErrorBoundarySharedProps & {\n fallback?: never;\n FallbackComponent: ComponentType<FallbackProps>;\n fallbackRender?: never;\n};\n\nexport type ErrorBoundaryPropsWithRender = ErrorBoundarySharedProps & {\n fallback?: never;\n FallbackComponent?: never;\n fallbackRender: typeof FallbackRender;\n};\n\nexport type ErrorBoundaryPropsWithFallback = ErrorBoundarySharedProps & {\n fallback: ReactElement<\n unknown,\n string | FunctionComponent | typeof Component\n > | null;\n FallbackComponent?: never;\n fallbackRender?: never;\n};\n\nexport type ErrorBoundaryProps =\n | ErrorBoundaryPropsWithFallback\n | ErrorBoundaryPropsWithComponent\n | ErrorBoundaryPropsWithRender;\n"],"names":[],"version":3,"file":"react-error-boundary.js.map"}
import {isValidElement as $hgUW1$isValidElement, createElement as $hgUW1$createElement, Component as $hgUW1$Component, createContext as $hgUW1$createContext, useContext as $hgUW1$useContext, useState as $hgUW1$useState, useMemo as $hgUW1$useMemo} from "react";
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
var $44d7e150ebc754d2$exports = {};
$parcel$export($44d7e150ebc754d2$exports, "ErrorBoundary", () => $44d7e150ebc754d2$export$e926676385687eaf);
var $ebb31c7feaa4405e$exports = {};
$parcel$export($ebb31c7feaa4405e$exports, "ErrorBoundaryContext", () => $ebb31c7feaa4405e$export$b16d9fb1a22de840);
const $ebb31c7feaa4405e$export$b16d9fb1a22de840 = (0, $hgUW1$createContext)(null);
const $44d7e150ebc754d2$var$initialState = {
didCatch: false,
error: null
};
class $44d7e150ebc754d2$export$e926676385687eaf extends (0, $hgUW1$Component) {
state = $44d7e150ebc754d2$var$initialState;
static getDerivedStateFromError(error) {
return {
didCatch: true,
error: error
};
}
resetErrorBoundary = (...args)=>{
const { error: error } = this.state;
if (error !== null) {
this.props.onReset?.({
args: args,
reason: "imperative-api"
});
this.setState($44d7e150ebc754d2$var$initialState);
}
};
componentDidCatch(error, info) {
this.props.onError?.(error, info);
}
componentDidUpdate(prevProps, prevState) {
const { didCatch: didCatch } = this.state;
const { resetKeys: resetKeys } = this.props;
// There's an edge case where if the thing that triggered the error happens to *also* be in the resetKeys array,
// we'd end up resetting the error boundary immediately.
// This would likely trigger a second error to be thrown.
// So we make sure that we don't check the resetKeys on the first call of cDU after the error is set.
if (didCatch && prevState.error !== null && $44d7e150ebc754d2$var$hasArrayChanged(prevProps.resetKeys, resetKeys)) {
this.props.onReset?.({
next: resetKeys,
prev: prevProps.resetKeys,
reason: "keys"
});
this.setState($44d7e150ebc754d2$var$initialState);
}
}
render() {
const { children: children , fallbackRender: fallbackRender , FallbackComponent: FallbackComponent , fallback: fallback } = this.props;
const { didCatch: didCatch , error: error } = this.state;
if (didCatch) {
const props = {
error: error,
resetErrorBoundary: this.resetErrorBoundary
};
if ((0, $hgUW1$isValidElement)(fallback)) return fallback;
else if (typeof fallbackRender === "function") return fallbackRender(props);
else if (FallbackComponent) return (0, $hgUW1$createElement)(FallbackComponent, props);
else throw new Error("react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop");
}
return (0, $hgUW1$createElement)((0, $ebb31c7feaa4405e$export$b16d9fb1a22de840).Provider, {
value: {
didCatch: didCatch,
error: error,
resetErrorBoundary: this.resetErrorBoundary
}
}, children);
}
}
function $44d7e150ebc754d2$var$hasArrayChanged(a = [], b = []) {
return a.length !== b.length || a.some((item, index)=>!Object.is(item, b[index]));
}
var $7c3c25b3f398a9d6$exports = {};
$parcel$export($7c3c25b3f398a9d6$exports, "useErrorBoundary", () => $7c3c25b3f398a9d6$export$c052f6604b7d51fe);
function $75c9d331f9c1ed1a$export$f20aa86254872370(value) {
if (value == null || typeof value.didCatch !== "boolean" || typeof value.resetErrorBoundary !== "function") throw new Error("ErrorBoundaryContext not found");
return true;
}
function $7c3c25b3f398a9d6$export$c052f6604b7d51fe() {
const context = (0, $hgUW1$useContext)((0, $ebb31c7feaa4405e$export$b16d9fb1a22de840));
(0, $75c9d331f9c1ed1a$export$f20aa86254872370)(context);
const [state, setState] = (0, $hgUW1$useState)({
error: null,
hasError: false
});
const memoized = (0, $hgUW1$useMemo)(()=>({
resetBoundary: ()=>{
context?.resetErrorBoundary();
setState({
error: null,
hasError: false
});
},
showBoundary: (error)=>setState({
error: error,
hasError: true
})
}), [
context?.resetErrorBoundary
]);
if (state.hasError) throw state.error;
return memoized;
}
var $62ff477d53f02a5b$exports = {};
$parcel$export($62ff477d53f02a5b$exports, "withErrorBoundary", () => $62ff477d53f02a5b$export$f0c7a449e0cfaec7);
function $62ff477d53f02a5b$export$f0c7a449e0cfaec7(Component, errorBoundaryProps) {
const Wrapped = (props)=>{
return (0, $hgUW1$createElement)((0, $44d7e150ebc754d2$export$e926676385687eaf), errorBoundaryProps, (0, $hgUW1$createElement)(Component, props));
};
// Format for display in DevTools
const name = Component.displayName || Component.name || "Unknown";
Wrapped.displayName = `withErrorBoundary(${name})`;
return Wrapped;
}
var $81c1b644006d48ec$exports = {};
export {$44d7e150ebc754d2$export$e926676385687eaf as ErrorBoundary, $ebb31c7feaa4405e$export$b16d9fb1a22de840 as ErrorBoundaryContext, $7c3c25b3f398a9d6$export$c052f6604b7d51fe as useErrorBoundary, $62ff477d53f02a5b$export$f0c7a449e0cfaec7 as withErrorBoundary};
//# sourceMappingURL=react-error-boundary.module.js.map
{"mappings":";;;;;;;;ACAA;;;;ACAA;AAQO,MAAM,4CACX,CAAA,GAAA,oBAAY,EAAmC,IAAI;;;ADOrD,MAAM,qCAAmC;IACvC,UAAU,KAAK;IACf,OAAO,IAAI;AACb;AAEO,MAAM,kDAAsB,CAAA,GAAA,gBAAS,AAAD;IAIzC,QAAQ,mCAAa;IAErB,OAAO,yBAAyB,KAAY,EAAE;QAC5C,OAAO;YAAE,UAAU,IAAI;mBAAE;QAAM;IACjC;IAEA,qBAAqB,CAAC,GAAG,OAAgB;QACvC,MAAM,SAAE,MAAK,EAAE,GAAG,IAAI,CAAC,KAAK;QAE5B,IAAI,UAAU,IAAI,EAAE;YAClB,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG;sBACnB;gBACA,QAAQ;YACV;YAEA,IAAI,CAAC,QAAQ,CAAC;QAChB,CAAC;IACH,EAA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IAElD,OAAO;AACT;;;;;","sources":["src/index.ts","src/ErrorBoundary.ts","src/ErrorBoundaryContext.ts","src/useErrorBoundary.ts","src/assertErrorBoundaryContext.ts","src/withErrorBoundary.ts","src/types.ts"],"sourcesContent":["export * from \"./ErrorBoundary\";\nexport * from \"./ErrorBoundaryContext\";\nexport * from \"./useErrorBoundary\";\nexport * from \"./withErrorBoundary\";\n\n// TypeScript types\nexport * from \"./types\";\n","import {\n Component,\n createElement,\n ErrorInfo,\n isValidElement,\n PropsWithChildren,\n PropsWithRef,\n} from \"react\";\nimport {\n ErrorBoundaryContextType,\n ErrorBoundaryContext,\n} from \"./ErrorBoundaryContext\";\nimport { ErrorBoundaryProps, FallbackProps } from \"./types\";\n\ntype ErrorBoundaryState = { didCatch: boolean; error: any };\n\nconst initialState: ErrorBoundaryState = {\n didCatch: false,\n error: null,\n};\n\nexport class ErrorBoundary extends Component<\n PropsWithRef<PropsWithChildren<ErrorBoundaryProps>>,\n ErrorBoundaryState\n> {\n state = initialState;\n\n static getDerivedStateFromError(error: Error) {\n return { didCatch: true, error };\n }\n\n resetErrorBoundary = (...args: any[]) => {\n const { error } = this.state;\n\n if (error !== null) {\n this.props.onReset?.({\n args,\n reason: \"imperative-api\",\n });\n\n this.setState(initialState);\n }\n };\n\n componentDidCatch(error: Error, info: ErrorInfo) {\n this.props.onError?.(error, info);\n }\n\n componentDidUpdate(\n prevProps: ErrorBoundaryProps,\n prevState: ErrorBoundaryState\n ) {\n const { didCatch } = this.state;\n const { resetKeys } = this.props;\n\n // There's an edge case where if the thing that triggered the error happens to *also* be in the resetKeys array,\n // we'd end up resetting the error boundary immediately.\n // This would likely trigger a second error to be thrown.\n // So we make sure that we don't check the resetKeys on the first call of cDU after the error is set.\n\n if (\n didCatch &&\n prevState.error !== null &&\n hasArrayChanged(prevProps.resetKeys, resetKeys)\n ) {\n this.props.onReset?.({\n next: resetKeys,\n prev: prevProps.resetKeys,\n reason: \"keys\",\n });\n\n this.setState(initialState);\n }\n }\n\n render() {\n const { children, fallbackRender, FallbackComponent, fallback } =\n this.props;\n const { didCatch, error } = this.state;\n\n if (didCatch) {\n const props: FallbackProps = {\n error,\n resetErrorBoundary: this.resetErrorBoundary,\n };\n\n if (isValidElement(fallback)) {\n return fallback;\n } else if (typeof fallbackRender === \"function\") {\n return fallbackRender(props);\n } else if (FallbackComponent) {\n return createElement(FallbackComponent, props);\n } else {\n throw new Error(\n \"react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop\"\n );\n }\n }\n\n return createElement(\n ErrorBoundaryContext.Provider,\n {\n value: {\n didCatch,\n error,\n resetErrorBoundary: this.resetErrorBoundary,\n },\n },\n children\n );\n }\n}\n\nfunction hasArrayChanged(a: any[] = [], b: any[] = []) {\n return (\n a.length !== b.length || a.some((item, index) => !Object.is(item, b[index]))\n );\n}\n","import { createContext } from \"react\";\n\nexport type ErrorBoundaryContextType = {\n didCatch: false;\n error: any;\n resetErrorBoundary: (...args: any[]) => void;\n};\n\nexport const ErrorBoundaryContext =\n createContext<ErrorBoundaryContextType | null>(null);\n","import { useContext, useMemo, useState } from \"react\";\nimport { assertErrorBoundaryContext } from \"./assertErrorBoundaryContext\";\nimport { ErrorBoundaryContext } from \"./ErrorBoundaryContext\";\n\nexport type UseErrorBoundaryApi<Error> = {\n resetBoundary: () => void;\n showBoundary: (error: Error) => void;\n};\n\nexport function useErrorBoundary<Error = any>(): UseErrorBoundaryApi<Error> {\n const context = useContext(ErrorBoundaryContext);\n\n assertErrorBoundaryContext(context);\n\n const [state, setState] = useState<{\n error: Error | null;\n hasError: boolean;\n }>({\n error: null,\n hasError: false,\n });\n\n const memoized = useMemo(\n () => ({\n resetBoundary: () => {\n context?.resetErrorBoundary();\n setState({ error: null, hasError: false });\n },\n showBoundary: (error: Error) =>\n setState({\n error,\n hasError: true,\n }),\n }),\n [context?.resetErrorBoundary]\n );\n\n if (state.hasError) {\n throw state.error;\n }\n\n return memoized;\n}\n","import { ErrorBoundaryContextType } from \"./ErrorBoundaryContext\";\n\nexport function assertErrorBoundaryContext(\n value: any\n): value is ErrorBoundaryContextType {\n if (\n value == null ||\n typeof value.didCatch !== \"boolean\" ||\n typeof value.resetErrorBoundary !== \"function\"\n ) {\n throw new Error(\"ErrorBoundaryContext not found\");\n }\n\n return true;\n}\n","import { ComponentType, createElement } from \"react\";\nimport { ErrorBoundary } from \"./ErrorBoundary\";\nimport { ErrorBoundaryProps } from \"./types\";\n\nexport function withErrorBoundary<Props extends Object>(\n Component: ComponentType<Props>,\n errorBoundaryProps: ErrorBoundaryProps\n): ComponentType<Props> {\n const Wrapped: ComponentType<Props> = (props: Props) => {\n return createElement(\n ErrorBoundary,\n errorBoundaryProps,\n createElement(Component, props)\n );\n };\n\n // Format for display in DevTools\n const name = Component.displayName || Component.name || \"Unknown\";\n Wrapped.displayName = `withErrorBoundary(${name})`;\n\n return Wrapped;\n}\n","import {\n Component,\n ComponentType,\n FunctionComponent,\n ReactElement,\n ReactNode,\n} from \"react\";\n\ndeclare function FallbackRender(props: FallbackProps): ReactNode;\n\nexport type FallbackProps = {\n error: any;\n resetErrorBoundary: (...args: any[]) => void;\n};\n\ntype ErrorBoundarySharedProps = {\n onError?: (error: Error, info: { componentStack: string }) => void;\n onReset?: (\n details:\n | { reason: \"imperative-api\"; args: any[] }\n | { reason: \"keys\"; prev: any[] | undefined; next: any[] | undefined }\n ) => void;\n resetKeys?: any[];\n};\n\nexport type ErrorBoundaryPropsWithComponent = ErrorBoundarySharedProps & {\n fallback?: never;\n FallbackComponent: ComponentType<FallbackProps>;\n fallbackRender?: never;\n};\n\nexport type ErrorBoundaryPropsWithRender = ErrorBoundarySharedProps & {\n fallback?: never;\n FallbackComponent?: never;\n fallbackRender: typeof FallbackRender;\n};\n\nexport type ErrorBoundaryPropsWithFallback = ErrorBoundarySharedProps & {\n fallback: ReactElement<\n unknown,\n string | FunctionComponent | typeof Component\n > | null;\n FallbackComponent?: never;\n fallbackRender?: never;\n};\n\nexport type ErrorBoundaryProps =\n | ErrorBoundaryPropsWithFallback\n | ErrorBoundaryPropsWithComponent\n | ErrorBoundaryPropsWithRender;\n"],"names":[],"version":3,"file":"react-error-boundary.module.js.map"}
+28
-33
{
"name": "react-error-boundary",
"version": "3.1.4",
"version": "4.0.0",
"description": "Simple reusable React error boundary component",
"main": "dist/react-error-boundary.cjs.js",
"module": "dist/react-error-boundary.esm.js",
"browser": "dist/react-error-boundary.umd.js",
"types": "dist/index.d.ts",
"sideEffects": false,
"keywords": [
"react",
"error boundary",
"error handling"
],
"author": "Brian Vaughn <brian.david.vaughn@gmail.com>",
"license": "MIT",
"engines": {
"node": ">=10",
"npm": ">=6"
},
"repository": {

@@ -25,6 +11,6 @@ "type": "git",

},
"bugs": {
"url": "https://github.com/bvaughn/react-error-boundary/issues"
},
"homepage": "https://github.com/bvaughn/react-error-boundary#readme",
"source": "src/index.ts",
"main": "dist/react-error-boundary.js",
"module": "dist/react-error-boundary.module.js",
"types": "dist/react-error-boundary.d.ts",
"files": [

@@ -34,9 +20,13 @@ "dist"

"scripts": {
"build": "kcd-scripts build --bundle",
"lint": "kcd-scripts lint",
"setup": "npm install && npm run validate -s",
"test": "kcd-scripts test",
"test:update": "npm test -- --updateSnapshot --coverage",
"typecheck": "kcd-scripts typecheck",
"validate": "kcd-scripts validate"
"clear": "npm run clear:parcel-cache & npm run clear:builds & npm run clear:node_modules",
"clear:builds": "rm -rf ./packages/*/dist",
"clear:parcel-cache": "rm -rf ./.parcel-cache",
"clear:node_modules": "rm -rf ./node_modules",
"prerelease": "rm -rf ./.parcel-cache && parcel build",
"prettier": "prettier --write \"**/*.{css,html,js,json,jsx,ts,tsx}\"",
"prettier:ci": "prettier --check \"**/*.{css,html,js,json,jsx,ts,tsx}\"",
"test": "jest",
"test:watch": "jest --watch",
"typescript": "tsc --noEmit",
"typescript:watch": "tsc --noEmit --watch"
},

@@ -47,10 +37,15 @@ "dependencies": {

"devDependencies": {
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.2.2",
"@testing-library/user-event": "^12.2.2",
"@parcel/core": "^2.8.3",
"@parcel/packager-ts": "^2.8.3",
"@parcel/transformer-typescript-types": "^2.8.3",
"@types/jest": "^26.0.15",
"@types/react": "^17.0.0",
"kcd-scripts": "^7.3.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"@types/react": "^18",
"@types/react-dom": "^18",
"jest": "^29.4.3",
"jest-environment-jsdom": "^29.4.3",
"parcel": "^2.8.3",
"prettier": "^2.8.6",
"react": "^18",
"react-dom": "^18",
"ts-jest": "^29.0.5",
"typescript": "^4.1.2"

@@ -57,0 +52,0 @@ },

+93
-397

@@ -1,446 +0,142 @@

<div align="center">
<h1>react-error-boundary</h1>
# react-error-boundary
<p>Simple reusable React error boundary component</p>
</div>
Reusable React [error boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary) component. Check out [this blog post](https://kentcdodds.com/blog/use-react-error-boundary-to-handle-errors-in-react) for examples of how this package can be used.
---
#### If you like this project, [buy me a coffee](http://givebrian.coffee/).
<!-- prettier-ignore-start -->
[![Build Status][build-badge]][build]
[![Code Coverage][coverage-badge]][coverage]
[![version][version-badge]][package]
[![downloads][downloads-badge]][npmtrends]
[![MIT License][license-badge]][license]
[![PRs Welcome][prs-badge]][prs]
[![Code of Conduct][coc-badge]][coc]
<!-- prettier-ignore-end -->
## Getting started
## The problem
```sh
# npm
npm install react-error-boundary
React [v16](https://reactjs.org/blog/2017/09/26/react-v16.0.html) introduced the
concept of [“error boundaries”](https://reactjs.org/docs/error-boundaries.html).
# yarn
yarn add react-error-boundary
```
## This solution
## API
This component provides a simple and reusable wrapper that you can use to wrap
around your components. Any rendering errors in your components hierarchy can
then be gracefully handled.
### `ErrorBoundary` component
Wrap an `ErrorBoundary` around other React components to "catch" errors and render a fallback UI. The component supports several ways to render a fallback (shown below).
Reading this blog post will help you understand what react-error-boundary does
for you:
[Use react-error-boundary to handle errors in React](https://kentcdodds.com/blog/use-react-error-boundary-to-handle-errors-in-react)
– How to simplify your React apps by handling React errors effectively with
react-error-boundary
#### `ErrorBoundary` with `fallback` prop
The simplest way to render a default "something went wrong" type error message.
```js
import { ErrorBoundary } from "react-error-boundary";
## Table of Contents
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [Installation](#installation)
- [Usage](#usage)
- [Error Recovery](#error-recovery)
- [API](#api)
- [`ErrorBoundary` props](#errorboundary-props)
- [`useErrorHandler(error?: unknown)`](#useerrorhandlererror-unknown)
- [Issues](#issues)
- [🐛 Bugs](#-bugs)
- [💡 Feature Requests](#-feature-requests)
- [LICENSE](#license)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Installation
This module is distributed via [npm][npm] which is bundled with [node][node] and
should be installed as one of your project's `dependencies`:
<ErrorBoundary fallback={<div>Something went wrong</div>}>
<ExampleApplication />
</ErrorBoundary>
```
npm install --save react-error-boundary
```
#### `ErrorBoundary` with `fallbackRender` prop
["Render prop"](https://react.dev/reference/react/Children#calling-a-render-prop-to-customize-rendering) function responsible for returning a fallback UI based on a thrown value.
```js
import { ErrorBoundary } from "react-error-boundary";
## Usage
function fallbackRender({ error, resetErrorBoundary }) {
// Call resetErrorBoundary() to reset the error boundary and retry the render.
The simplest way to use `<ErrorBoundary>` is to wrap it around any component
that may throw an error. This will handle errors thrown by that component and
its descendants too.
```jsx
import {ErrorBoundary} from 'react-error-boundary'
function ErrorFallback({error, resetErrorBoundary}) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
<pre style={{ color: "red" }}>{error.message}</pre>
</div>
)
);
}
const ui = (
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => {
// reset the state of your app so the error doesn't happen again
}}
>
<ComponentThatMayError />
</ErrorBoundary>
)
<ErrorBoundary
fallbackRender={fallbackRender}
onReset={(details) => {
// Reset the state of your app so the error doesn't happen again
}}
>
<ExampleApplication />
</ErrorBoundary>;
```
#### `ErrorBoundary` with `FallbackComponent` prop
React component responsible for returning a fallback UI based on a thrown value.
```js
import { ErrorBoundary } from "react-error-boundary";
You can react to errors (e.g. for logging) by providing an `onError` callback:
function Fallback({ error, resetErrorBoundary }) {
// Call resetErrorBoundary() to reset the error boundary and retry the render.
```jsx
import {ErrorBoundary} from 'react-error-boundary'
const myErrorHandler = (error: Error, info: {componentStack: string}) => {
// Do something with the error
// E.g. log to an error logging client here
}
const ui = (
<ErrorBoundary FallbackComponent={ErrorFallback} onError={myErrorHandler}>
<ComponentThatMayError />
</ErrorBoundary>,
)
```
You can also use it as a
[higher-order component](https://reactjs.org/docs/higher-order-components.html):
```jsx
import {withErrorBoundary} from 'react-error-boundary'
const ComponentWithErrorBoundary = withErrorBoundary(ComponentThatMayError, {
FallbackComponent: ErrorBoundaryFallbackComponent,
onError(error, info) {
// Do something with the error
// E.g. log to an error logging client here
},
})
const ui = <ComponentWithErrorBoundary />
```
### Error Recovery
In the event of an error if you want to recover from that error and allow the
user to "try again" or continue with their work, you'll need a way to reset the
ErrorBoundary's internal state. You can do this various ways, but here's the
most idiomatic approach:
```jsx
function ErrorFallback({error, resetErrorBoundary}) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
<pre style={{ color: "red" }}>{error.message}</pre>
</div>
)
);
}
function Bomb() {
throw new Error('💥 CABOOM 💥')
}
function App() {
const [explode, setExplode] = React.useState(false)
return (
<div>
<button onClick={() => setExplode(e => !e)}>toggle explode</button>
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => setExplode(false)}
resetKeys={[explode]}
>
{explode ? <Bomb /> : null}
</ErrorBoundary>
</div>
)
}
<ErrorBoundary
FallbackComponent={Fallback}
onReset={(details) => {
// Reset the state of your app so the error doesn't happen again
}}
>
<ExampleApplication />
</ErrorBoundary>;
```
So, with this setup, you've got a button which when clicked will trigger an
error. Clicking the button again will trigger a re-render which recovers from
the error (we no longer render the `<Bomb />`). We also pass the `resetKeys`
prop which is an array of elements for the `ErrorBoundary` to check each render
(if there's currently an error state). If any of those elements change between
renders, then the `ErrorBoundary` will reset the state which will re-render the
children.
#### Logging errors with `onError`
We have the `onReset` prop so that if the user clicks the "Try again" button we
have an opportunity to re-initialize our state into a good place before
attempting to re-render the children.
```js
import { ErrorBoundary } from "react-error-boundary";
This combination allows us both the opportunity to give the user something
specific to do to recover from the error, and recover from the error by
interacting with other areas of the app that might fix things for us. It's hard
to describe here, but hopefully it makes sense when you apply it to your
specific scenario.
const logError = (error: Error, info: { componentStack: string }) => {
// Do something with the error, e.g. log to an external API
};
## API
### `ErrorBoundary` props
#### `children`
This is what you want rendered when everything's working fine. If there's an
error that React can handle within the children of the `ErrorBoundary`, the
`ErrorBoundary` will catch that and allow you to handle it gracefully.
#### `FallbackComponent`
This is a component you want rendered in the event of an error. As props it will
be passed the `error` and `resetErrorBoundary` (which will reset the error
boundary's state when called, useful for a "try again" button when used in
combination with the `onReset` prop).
This is required if no `fallback` or `fallbackRender` prop is provided.
#### `fallbackRender`
This is a render-prop based API that allows you to inline your error fallback UI
into the component that's using the `ErrorBoundary`. This is useful if you need
access to something that's in the scope of the component you're using.
It will be called with an object that has `error` and `resetErrorBoundary`:
```jsx
const ui = (
<ErrorBoundary
fallbackRender={({error, resetErrorBoundary}) => (
<div role="alert">
<div>Oh no</div>
<pre>{error.message}</pre>
<button
onClick={() => {
// this next line is why the fallbackRender is useful
resetComponentState()
// though you could accomplish this with a combination
// of the FallbackCallback and onReset props as well.
resetErrorBoundary()
}}
>
Try again
</button>
</div>
)}
>
<ComponentThatMayError />
<ErrorBoundary FallbackComponent={ErrorFallback} onError={logError}>
<ExampleApplication />
</ErrorBoundary>
)
);
```
I know what you're thinking: I thought we ditched render props when hooks came
around. Unfortunately, the current React Error Boundary API only supports class
components at the moment, so render props are the best solution we have to this
problem.
### `useErrorBoundary` hook
Convenience hook for imperatively showing or dismissing error boundaries.
This is required if no `FallbackComponent` or `fallback` prop is provided.
React only handles errors thrown during render or during component lifecycle methods (e.g. effects and did-mount/did-update). Errors thrown in event handlers, or after async code has run, will not be caught.
#### `fallback`
This hook can be used to pass those errors to the nearest error boundary:
In the spirit of consistency with the `React.Suspense` component, we also
support a simple `fallback` prop which you can use for a generic fallback. This
will not be passed any props so you can't show the user anything actually useful
though, so it's not really recommended.
```js
import { useErrorBoundary } from "react-error-boundary";
```jsx
const ui = (
<ErrorBoundary fallback={<div>Oh no</div>}>
<ComponentThatMayError />
</ErrorBoundary>
)
```
function Example() {
const { resetBoundary, showErrorBoundary } = useErrorBoundary();
#### `onError`
This will be called when there's been an error that the `ErrorBoundary` has
handled. It will be called with two arguments: `error`, `info`.
#### `onReset`
This will be called immediately before the `ErrorBoundary` resets it's internal
state (which will result in rendering the `children` again). You should use this
to ensure that re-rendering the children will not result in a repeat of the same
error happening again.
`onReset` will be called with whatever `resetErrorBoundary` is called with.
**Important**: `onReset` will _not_ be called when reset happens from a change
in `resetKeys`. Use `onResetKeysChange` for that.
#### `resetKeys`
Sometimes an error happens as a result of local state to the component that's
rendering the error. If this is the case, then you can pass `resetKeys` which is
an array of values. If the `ErrorBoundary` is in an error state, then it will
check these values each render and if they change from one render to the next,
then it will reset automatically (triggering a re-render of the `children`).
See the recovery examples above.
#### `onResetKeysChange`
This is called when the `resetKeys` are changed (triggering a reset of the
`ErrorBoundary`). It's called with the `prevResetKeys` and the `resetKeys`.
### `useErrorHandler(error?: unknown)`
React's error boundaries feature is limited in that the boundaries can only
handle errors thrown during React's lifecycles. To quote
[the React docs on Error Boundaries](https://reactjs.org/docs/error-boundaries.html):
> Error boundaries do not catch errors for:
>
> - Event handlers
> ([learn more](https://reactjs.org/docs/error-boundaries.html#how-about-event-handlers))
> - Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
> - Server side rendering
> - Errors thrown in the error boundary itself (rather than its children)
This means you have to handle those errors yourself, but you probably would like
to reuse the error boundaries you worked hard on creating for those kinds of
errors as well. This is what `useErrorHandler` is for.
There are two ways to use `useErrorHandler`:
1. `const handleError = useErrorHandler()`: call `handleError(theError)`
2. `useErrorHandler(error)`: useful if you are managing the error state yourself
or get it from another hook.
Here's an example:
```javascript
import { useErrorHandler } from 'react-error-boundary'
function Greeting() {
const [greeting, setGreeting] = React.useState(null)
const handleError = useErrorHandler()
function handleSubmit(event) {
event.preventDefault()
const name = event.target.elements.name.value
useEffect(() => {
fetchGreeting(name).then(
newGreeting => setGreeting(newGreeting),
handleError,
)
}
response => {
// Set data in state and re-render
},
error => {
// Show error boundary
showErrorBoundary(error);
}
);
});
return greeting ? (
<div>{greeting}</div>
) : (
<form onSubmit={handleSubmit}>
<label>Name</label>
<input id="name" />
<button type="submit">get a greeting</button>
</form>
)
// Render ...
}
```
> Note, in case it's not clear what's happening here, you could also write
> `handleSubmit` like this:
### `withErrorBoundary` HOC
This package can also be used as a [higher-order component](https://legacy.reactjs.org/docs/higher-order-components.html) that accepts all of the same props as above:
```javascript
function handleSubmit(event) {
event.preventDefault()
const name = event.target.elements.name.value
fetchGreeting(name).then(
newGreeting => setGreeting(newGreeting),
error => handleError(error),
)
}
```
```js
import {withErrorBoundary} from 'react-error-boundary'
Alternatively, let's say you're using a hook that gives you the error:
const ComponentWithErrorBoundary = withErrorBoundary(ExampleComponent, {
fallback: <div>Something went wrong</div>,
onError(error, info) {
// Do something with the error
// E.g. log to an error logging client here
},
})
```javascript
import { useErrorHandler } from 'react-error-boundary'
function Greeting() {
const [name, setName] = React.useState('')
const {greeting, error} = useGreeting(name)
useErrorHandler(error)
function handleSubmit(event) {
event.preventDefault()
const name = event.target.elements.name.value
setName(name)
}
return greeting ? (
<div>{greeting}</div>
) : (
<form onSubmit={handleSubmit}>
<label>Name</label>
<input id="name" />
<button type="submit">get a greeting</button>
</form>
)
}
```
In this case, if the `error` is ever set to a truthy value, then it will be
propagated to the nearest error boundary.
In either case, you could handle those errors like this:
```javascript
const ui = (
<ErrorBoundary FallbackComponent={ErrorFallback}>
<Greeting />
</ErrorBoundary>
)
```
And now that'll handle your runtime errors as well as the async errors in the
`fetchGreeting` or `useGreeting` code.
## Issues
_Looking to contribute? Look for the [Good First Issue][good-first-issue]
label._
### 🐛 Bugs
Please file an issue for bugs, missing documentation, or unexpected behavior.
[**See Bugs**][bugs]
### 💡 Feature Requests
Please file an issue to suggest new features. Vote on feature requests by adding
a 👍. This helps maintainers prioritize what to work on.
[**See Feature Requests**][requests]
## LICENSE
MIT
<!-- prettier-ignore-start -->
[npm]: https://www.npmjs.com
[node]: https://nodejs.org
[build-badge]: https://img.shields.io/github/workflow/status/bvaughn/react-error-boundary/validate?logo=github&style=flat-square
[build]: https://github.com/bvaughn/react-error-boundary/actions?query=workflow%3Avalidate
[coverage-badge]: https://img.shields.io/codecov/c/github/bvaughn/react-error-boundary.svg?style=flat-square
[coverage]: https://codecov.io/github/bvaughn/react-error-boundary
[version-badge]: https://img.shields.io/npm/v/react-error-boundary.svg?style=flat-square
[package]: https://www.npmjs.com/package/react-error-boundary
[downloads-badge]: https://img.shields.io/npm/dm/react-error-boundary.svg?style=flat-square
[npmtrends]: https://www.npmtrends.com/react-error-boundary
[license-badge]: https://img.shields.io/npm/l/react-error-boundary.svg?style=flat-square
[license]: https://github.com/bvaughn/react-error-boundary/blob/master/LICENSE
[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
[prs]: https://makeapullrequest.com
[coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square
[coc]: https://github.com/bvaughn/react-error-boundary/blob/master/CODE_OF_CONDUCT.md
[bugs]: https://github.com/bvaughn/react-error-boundary/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Acreated-desc+label%3Abug
[requests]: https://github.com/bvaughn/react-error-boundary/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement
[good-first-issue]: https://github.com/bvaughn/react-error-boundary/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement+label%3A%22good+first+issue%22
<!-- prettier-ignore-end -->
// Can be rendered as <ComponentWithErrorBoundary {...props} />
```
# CHANGELOG
The changelog is automatically updated using
[semantic-release](https://github.com/semantic-release/semantic-release). You
can see it on the [releases page](../../releases).
import * as React from 'react';
interface FallbackProps {
error: Error;
resetErrorBoundary: (...args: Array<unknown>) => void;
}
interface ErrorBoundaryPropsWithComponent {
onResetKeysChange?: (prevResetKeys: Array<unknown> | undefined, resetKeys: Array<unknown> | undefined) => void;
onReset?: (...args: Array<unknown>) => void;
onError?: (error: Error, info: {
componentStack: string;
}) => void;
resetKeys?: Array<unknown>;
fallback?: never;
FallbackComponent: React.ComponentType<FallbackProps>;
fallbackRender?: never;
}
declare function FallbackRender(props: FallbackProps): React.ReactElement<unknown, string | React.FunctionComponent | typeof React.Component> | null;
interface ErrorBoundaryPropsWithRender {
onResetKeysChange?: (prevResetKeys: Array<unknown> | undefined, resetKeys: Array<unknown> | undefined) => void;
onReset?: (...args: Array<unknown>) => void;
onError?: (error: Error, info: {
componentStack: string;
}) => void;
resetKeys?: Array<unknown>;
fallback?: never;
FallbackComponent?: never;
fallbackRender: typeof FallbackRender;
}
interface ErrorBoundaryPropsWithFallback {
onResetKeysChange?: (prevResetKeys: Array<unknown> | undefined, resetKeys: Array<unknown> | undefined) => void;
onReset?: (...args: Array<unknown>) => void;
onError?: (error: Error, info: {
componentStack: string;
}) => void;
resetKeys?: Array<unknown>;
fallback: React.ReactElement<unknown, string | React.FunctionComponent | typeof React.Component> | null;
FallbackComponent?: never;
fallbackRender?: never;
}
declare type ErrorBoundaryProps = ErrorBoundaryPropsWithFallback | ErrorBoundaryPropsWithComponent | ErrorBoundaryPropsWithRender;
declare type ErrorBoundaryState = {
error: Error | null;
};
declare class ErrorBoundary extends React.Component<React.PropsWithRef<React.PropsWithChildren<ErrorBoundaryProps>>, ErrorBoundaryState> {
static getDerivedStateFromError(error: Error): {
error: Error;
};
state: ErrorBoundaryState;
resetErrorBoundary: (...args: Array<unknown>) => void;
reset(): void;
componentDidCatch(error: Error, info: React.ErrorInfo): void;
componentDidUpdate(prevProps: ErrorBoundaryProps, prevState: ErrorBoundaryState): void;
render(): React.ReactNode;
}
declare function withErrorBoundary<P>(Component: React.ComponentType<P>, errorBoundaryProps: ErrorBoundaryProps): React.ComponentType<P>;
declare function useErrorHandler(givenError?: unknown): (error: unknown) => void;
export { ErrorBoundary, withErrorBoundary, useErrorHandler };
export type { FallbackProps, ErrorBoundaryPropsWithComponent, ErrorBoundaryPropsWithRender, ErrorBoundaryPropsWithFallback, ErrorBoundaryProps, };
export * from "../dist/index";
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var _inheritsLoose = require('@babel/runtime/helpers/inheritsLoose');
var React = require('react');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var _inheritsLoose__default = /*#__PURE__*/_interopDefaultLegacy(_inheritsLoose);
var React__namespace = /*#__PURE__*/_interopNamespace(React);
var changedArray = function changedArray(a, b) {
if (a === void 0) {
a = [];
}
if (b === void 0) {
b = [];
}
return a.length !== b.length || a.some(function (item, index) {
return !Object.is(item, b[index]);
});
};
var initialState = {
error: null
};
var ErrorBoundary = /*#__PURE__*/function (_React$Component) {
_inheritsLoose__default["default"](ErrorBoundary, _React$Component);
function ErrorBoundary() {
var _this;
for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
_args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
_this.state = initialState;
_this.resetErrorBoundary = function () {
var _this$props;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this.props.onReset == null ? void 0 : (_this$props = _this.props).onReset.apply(_this$props, args);
_this.reset();
};
return _this;
}
ErrorBoundary.getDerivedStateFromError = function getDerivedStateFromError(error) {
return {
error: error
};
};
var _proto = ErrorBoundary.prototype;
_proto.reset = function reset() {
this.setState(initialState);
};
_proto.componentDidCatch = function componentDidCatch(error, info) {
var _this$props$onError, _this$props2;
(_this$props$onError = (_this$props2 = this.props).onError) == null ? void 0 : _this$props$onError.call(_this$props2, error, info);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
var error = this.state.error;
var resetKeys = this.props.resetKeys; // There's an edge case where if the thing that triggered the error
// happens to *also* be in the resetKeys array, we'd end up resetting
// the error boundary immediately. This would likely trigger a second
// error to be thrown.
// So we make sure that we don't check the resetKeys on the first call
// of cDU after the error is set
if (error !== null && prevState.error !== null && changedArray(prevProps.resetKeys, resetKeys)) {
var _this$props$onResetKe, _this$props3;
(_this$props$onResetKe = (_this$props3 = this.props).onResetKeysChange) == null ? void 0 : _this$props$onResetKe.call(_this$props3, prevProps.resetKeys, resetKeys);
this.reset();
}
};
_proto.render = function render() {
var error = this.state.error;
var _this$props4 = this.props,
fallbackRender = _this$props4.fallbackRender,
FallbackComponent = _this$props4.FallbackComponent,
fallback = _this$props4.fallback;
if (error !== null) {
var _props = {
error: error,
resetErrorBoundary: this.resetErrorBoundary
};
if ( /*#__PURE__*/React__namespace.isValidElement(fallback)) {
return fallback;
} else if (typeof fallbackRender === 'function') {
return fallbackRender(_props);
} else if (FallbackComponent) {
return /*#__PURE__*/React__namespace.createElement(FallbackComponent, _props);
} else {
throw new Error('react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop');
}
}
return this.props.children;
};
return ErrorBoundary;
}(React__namespace.Component);
function withErrorBoundary(Component, errorBoundaryProps) {
var Wrapped = function Wrapped(props) {
return /*#__PURE__*/React__namespace.createElement(ErrorBoundary, errorBoundaryProps, /*#__PURE__*/React__namespace.createElement(Component, props));
}; // Format for display in DevTools
var name = Component.displayName || Component.name || 'Unknown';
Wrapped.displayName = "withErrorBoundary(" + name + ")";
return Wrapped;
}
function useErrorHandler(givenError) {
var _React$useState = React__namespace.useState(null),
error = _React$useState[0],
setError = _React$useState[1];
if (givenError != null) throw givenError;
if (error != null) throw error;
return setError;
}
/*
eslint
@typescript-eslint/sort-type-union-intersection-members: "off",
@typescript-eslint/no-throw-literal: "off",
@typescript-eslint/prefer-nullish-coalescing: "off"
*/
exports.ErrorBoundary = ErrorBoundary;
exports.useErrorHandler = useErrorHandler;
exports.withErrorBoundary = withErrorBoundary;
export * from "../dist/index";
import _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose';
import * as React from 'react';
var changedArray = function changedArray(a, b) {
if (a === void 0) {
a = [];
}
if (b === void 0) {
b = [];
}
return a.length !== b.length || a.some(function (item, index) {
return !Object.is(item, b[index]);
});
};
var initialState = {
error: null
};
var ErrorBoundary = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(ErrorBoundary, _React$Component);
function ErrorBoundary() {
var _this;
for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
_args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
_this.state = initialState;
_this.resetErrorBoundary = function () {
var _this$props;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this.props.onReset == null ? void 0 : (_this$props = _this.props).onReset.apply(_this$props, args);
_this.reset();
};
return _this;
}
ErrorBoundary.getDerivedStateFromError = function getDerivedStateFromError(error) {
return {
error: error
};
};
var _proto = ErrorBoundary.prototype;
_proto.reset = function reset() {
this.setState(initialState);
};
_proto.componentDidCatch = function componentDidCatch(error, info) {
var _this$props$onError, _this$props2;
(_this$props$onError = (_this$props2 = this.props).onError) == null ? void 0 : _this$props$onError.call(_this$props2, error, info);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
var error = this.state.error;
var resetKeys = this.props.resetKeys; // There's an edge case where if the thing that triggered the error
// happens to *also* be in the resetKeys array, we'd end up resetting
// the error boundary immediately. This would likely trigger a second
// error to be thrown.
// So we make sure that we don't check the resetKeys on the first call
// of cDU after the error is set
if (error !== null && prevState.error !== null && changedArray(prevProps.resetKeys, resetKeys)) {
var _this$props$onResetKe, _this$props3;
(_this$props$onResetKe = (_this$props3 = this.props).onResetKeysChange) == null ? void 0 : _this$props$onResetKe.call(_this$props3, prevProps.resetKeys, resetKeys);
this.reset();
}
};
_proto.render = function render() {
var error = this.state.error;
var _this$props4 = this.props,
fallbackRender = _this$props4.fallbackRender,
FallbackComponent = _this$props4.FallbackComponent,
fallback = _this$props4.fallback;
if (error !== null) {
var _props = {
error: error,
resetErrorBoundary: this.resetErrorBoundary
};
if ( /*#__PURE__*/React.isValidElement(fallback)) {
return fallback;
} else if (typeof fallbackRender === 'function') {
return fallbackRender(_props);
} else if (FallbackComponent) {
return /*#__PURE__*/React.createElement(FallbackComponent, _props);
} else {
throw new Error('react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop');
}
}
return this.props.children;
};
return ErrorBoundary;
}(React.Component);
function withErrorBoundary(Component, errorBoundaryProps) {
var Wrapped = function Wrapped(props) {
return /*#__PURE__*/React.createElement(ErrorBoundary, errorBoundaryProps, /*#__PURE__*/React.createElement(Component, props));
}; // Format for display in DevTools
var name = Component.displayName || Component.name || 'Unknown';
Wrapped.displayName = "withErrorBoundary(" + name + ")";
return Wrapped;
}
function useErrorHandler(givenError) {
var _React$useState = React.useState(null),
error = _React$useState[0],
setError = _React$useState[1];
if (givenError != null) throw givenError;
if (error != null) throw error;
return setError;
}
/*
eslint
@typescript-eslint/sort-type-union-intersection-members: "off",
@typescript-eslint/no-throw-literal: "off",
@typescript-eslint/prefer-nullish-coalescing: "off"
*/
export { ErrorBoundary, useErrorHandler, withErrorBoundary };
export * from "../dist/index";
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactErrorBoundary = {}, global.React));
})(this, (function (exports, React) { 'use strict';
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespace(React);
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
_setPrototypeOf(subClass, superClass);
}
var changedArray = function changedArray(a, b) {
if (a === void 0) {
a = [];
}
if (b === void 0) {
b = [];
}
return a.length !== b.length || a.some(function (item, index) {
return !Object.is(item, b[index]);
});
};
var initialState = {
error: null
};
var ErrorBoundary = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(ErrorBoundary, _React$Component);
function ErrorBoundary() {
var _this;
for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
_args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
_this.state = initialState;
_this.resetErrorBoundary = function () {
var _this$props;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this.props.onReset == null ? void 0 : (_this$props = _this.props).onReset.apply(_this$props, args);
_this.reset();
};
return _this;
}
ErrorBoundary.getDerivedStateFromError = function getDerivedStateFromError(error) {
return {
error: error
};
};
var _proto = ErrorBoundary.prototype;
_proto.reset = function reset() {
this.setState(initialState);
};
_proto.componentDidCatch = function componentDidCatch(error, info) {
var _this$props$onError, _this$props2;
(_this$props$onError = (_this$props2 = this.props).onError) == null ? void 0 : _this$props$onError.call(_this$props2, error, info);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
var error = this.state.error;
var resetKeys = this.props.resetKeys; // There's an edge case where if the thing that triggered the error
// happens to *also* be in the resetKeys array, we'd end up resetting
// the error boundary immediately. This would likely trigger a second
// error to be thrown.
// So we make sure that we don't check the resetKeys on the first call
// of cDU after the error is set
if (error !== null && prevState.error !== null && changedArray(prevProps.resetKeys, resetKeys)) {
var _this$props$onResetKe, _this$props3;
(_this$props$onResetKe = (_this$props3 = this.props).onResetKeysChange) == null ? void 0 : _this$props$onResetKe.call(_this$props3, prevProps.resetKeys, resetKeys);
this.reset();
}
};
_proto.render = function render() {
var error = this.state.error;
var _this$props4 = this.props,
fallbackRender = _this$props4.fallbackRender,
FallbackComponent = _this$props4.FallbackComponent,
fallback = _this$props4.fallback;
if (error !== null) {
var _props = {
error: error,
resetErrorBoundary: this.resetErrorBoundary
};
if ( /*#__PURE__*/React__namespace.isValidElement(fallback)) {
return fallback;
} else if (typeof fallbackRender === 'function') {
return fallbackRender(_props);
} else if (FallbackComponent) {
return /*#__PURE__*/React__namespace.createElement(FallbackComponent, _props);
} else {
throw new Error('react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop');
}
}
return this.props.children;
};
return ErrorBoundary;
}(React__namespace.Component);
function withErrorBoundary(Component, errorBoundaryProps) {
var Wrapped = function Wrapped(props) {
return /*#__PURE__*/React__namespace.createElement(ErrorBoundary, errorBoundaryProps, /*#__PURE__*/React__namespace.createElement(Component, props));
}; // Format for display in DevTools
var name = Component.displayName || Component.name || 'Unknown';
Wrapped.displayName = "withErrorBoundary(" + name + ")";
return Wrapped;
}
function useErrorHandler(givenError) {
var _React$useState = React__namespace.useState(null),
error = _React$useState[0],
setError = _React$useState[1];
if (givenError != null) throw givenError;
if (error != null) throw error;
return setError;
}
/*
eslint
@typescript-eslint/sort-type-union-intersection-members: "off",
@typescript-eslint/no-throw-literal: "off",
@typescript-eslint/prefer-nullish-coalescing: "off"
*/
exports.ErrorBoundary = ErrorBoundary;
exports.useErrorHandler = useErrorHandler;
exports.withErrorBoundary = withErrorBoundary;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=react-error-boundary.umd.js.map
{"version":3,"file":"react-error-boundary.umd.js","sources":["../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","../src/index.tsx"],"sourcesContent":["export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","import * as React from 'react'\n\nconst changedArray = (a: Array<unknown> = [], b: Array<unknown> = []) =>\n a.length !== b.length || a.some((item, index) => !Object.is(item, b[index]))\n\ninterface FallbackProps {\n error: Error\n resetErrorBoundary: (...args: Array<unknown>) => void\n}\n\ninterface ErrorBoundaryPropsWithComponent {\n onResetKeysChange?: (\n prevResetKeys: Array<unknown> | undefined,\n resetKeys: Array<unknown> | undefined,\n ) => void\n onReset?: (...args: Array<unknown>) => void\n onError?: (error: Error, info: {componentStack: string}) => void\n resetKeys?: Array<unknown>\n fallback?: never\n FallbackComponent: React.ComponentType<FallbackProps>\n fallbackRender?: never\n}\n\ndeclare function FallbackRender(\n props: FallbackProps,\n): React.ReactElement<\n unknown,\n string | React.FunctionComponent | typeof React.Component\n> | null\n\ninterface ErrorBoundaryPropsWithRender {\n onResetKeysChange?: (\n prevResetKeys: Array<unknown> | undefined,\n resetKeys: Array<unknown> | undefined,\n ) => void\n onReset?: (...args: Array<unknown>) => void\n onError?: (error: Error, info: {componentStack: string}) => void\n resetKeys?: Array<unknown>\n fallback?: never\n FallbackComponent?: never\n fallbackRender: typeof FallbackRender\n}\n\ninterface ErrorBoundaryPropsWithFallback {\n onResetKeysChange?: (\n prevResetKeys: Array<unknown> | undefined,\n resetKeys: Array<unknown> | undefined,\n ) => void\n onReset?: (...args: Array<unknown>) => void\n onError?: (error: Error, info: {componentStack: string}) => void\n resetKeys?: Array<unknown>\n fallback: React.ReactElement<\n unknown,\n string | React.FunctionComponent | typeof React.Component\n > | null\n FallbackComponent?: never\n fallbackRender?: never\n}\n\ntype ErrorBoundaryProps =\n | ErrorBoundaryPropsWithFallback\n | ErrorBoundaryPropsWithComponent\n | ErrorBoundaryPropsWithRender\n\ntype ErrorBoundaryState = {error: Error | null}\n\nconst initialState: ErrorBoundaryState = {error: null}\n\nclass ErrorBoundary extends React.Component<\n React.PropsWithRef<React.PropsWithChildren<ErrorBoundaryProps>>,\n ErrorBoundaryState\n> {\n static getDerivedStateFromError(error: Error) {\n return {error}\n }\n\n state = initialState\n resetErrorBoundary = (...args: Array<unknown>) => {\n this.props.onReset?.(...args)\n this.reset()\n }\n\n reset() {\n this.setState(initialState)\n }\n\n componentDidCatch(error: Error, info: React.ErrorInfo) {\n this.props.onError?.(error, info)\n }\n\n componentDidUpdate(\n prevProps: ErrorBoundaryProps,\n prevState: ErrorBoundaryState,\n ) {\n const {error} = this.state\n const {resetKeys} = this.props\n\n // There's an edge case where if the thing that triggered the error\n // happens to *also* be in the resetKeys array, we'd end up resetting\n // the error boundary immediately. This would likely trigger a second\n // error to be thrown.\n // So we make sure that we don't check the resetKeys on the first call\n // of cDU after the error is set\n\n if (\n error !== null &&\n prevState.error !== null &&\n changedArray(prevProps.resetKeys, resetKeys)\n ) {\n this.props.onResetKeysChange?.(prevProps.resetKeys, resetKeys)\n this.reset()\n }\n }\n\n render() {\n const {error} = this.state\n\n const {fallbackRender, FallbackComponent, fallback} = this.props\n\n if (error !== null) {\n const props = {\n error,\n resetErrorBoundary: this.resetErrorBoundary,\n }\n if (React.isValidElement(fallback)) {\n return fallback\n } else if (typeof fallbackRender === 'function') {\n return fallbackRender(props)\n } else if (FallbackComponent) {\n return <FallbackComponent {...props} />\n } else {\n throw new Error(\n 'react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop',\n )\n }\n }\n\n return this.props.children\n }\n}\n\nfunction withErrorBoundary<P>(\n Component: React.ComponentType<P>,\n errorBoundaryProps: ErrorBoundaryProps,\n): React.ComponentType<P> {\n const Wrapped: React.ComponentType<P> = props => {\n return (\n <ErrorBoundary {...errorBoundaryProps}>\n <Component {...props} />\n </ErrorBoundary>\n )\n }\n\n // Format for display in DevTools\n const name = Component.displayName || Component.name || 'Unknown'\n Wrapped.displayName = `withErrorBoundary(${name})`\n\n return Wrapped\n}\n\nfunction useErrorHandler(givenError?: unknown): (error: unknown) => void {\n const [error, setError] = React.useState<unknown>(null)\n if (givenError != null) throw givenError\n if (error != null) throw error\n return setError\n}\n\nexport {ErrorBoundary, withErrorBoundary, useErrorHandler}\nexport type {\n FallbackProps,\n ErrorBoundaryPropsWithComponent,\n ErrorBoundaryPropsWithRender,\n ErrorBoundaryPropsWithFallback,\n ErrorBoundaryProps,\n}\n\n/*\neslint\n @typescript-eslint/sort-type-union-intersection-members: \"off\",\n @typescript-eslint/no-throw-literal: \"off\",\n @typescript-eslint/prefer-nullish-coalescing: \"off\"\n*/\n"],"names":["_setPrototypeOf","o","p","Object","setPrototypeOf","__proto__","_inheritsLoose","subClass","superClass","prototype","create","constructor","changedArray","a","b","length","some","item","index","is","initialState","error","ErrorBoundary","state","resetErrorBoundary","args","props","onReset","reset","getDerivedStateFromError","setState","componentDidCatch","info","onError","componentDidUpdate","prevProps","prevState","resetKeys","onResetKeysChange","render","fallbackRender","FallbackComponent","fallback","React","isValidElement","Error","children","Component","withErrorBoundary","errorBoundaryProps","Wrapped","name","display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AAqBF,QAArB,CAAJ,EAAoC;EAClC,eAAOA,QAAP;EACD,OAFD,MAEO,IAAI,OAAOF,cAAP,KAA0B,UAA9B,EAA0C;EAC/C,eAAOA,cAAc,CAACd,MAAD,CAArB;EACD,OAFM,MAEA,IAAIe,iBAAJ,EAAuB;EAC5B,4BAAOE,+BAAC,iBAAD,EAAuBjB,MAAvB,CAAP;EACD,OAFM,MAEA;EACL,cAAM,IAAImB,KAAJ,CACJ,4FADI,CAAN;EAGD;EACF;;EAED,WAAO,KAAKnB,KAAL,CAAWoB,QAAlB;EACD;;;IAtEyBH,gBAAK,CAACI;;EAyElC,SAASC,iBAAT,CACED,SADF,EAEEE,kBAFF,EAG0B;EACxB,MAAMC,OAA+B,GAAG,SAAlCA,OAAkC,CAAAxB,KAAK,EAAI;EAC/C,wBACEiB,+BAAC,aAAD,EAAmBM,kBAAnB,eACEN,+BAAC,SAAD,EAAejB,KAAf,CADF,CADF;EAKD,GAND,CADwB;;;EAUxB,MAAMyB,IAAI,GAAGJ,SAAS,CAACK,WAAV,IAAyBL,SAAS,CAACI,IAAnC,IAA2C,SAAxD;EACAD,EAAAA,OAAO,CAACE,WAAR,0BAA2CD,IAA3C;EAEA,SAAOD,OAAP;EACD;;EAED,SAASG,eAAT,CAAyBC,UAAzB,EAAyE;EACvE,wBAA0BX,gBAAK,CAACY,QAAN,CAAwB,IAAxB,CAA1B;EAAA,MAAOlC,KAAP;EAAA,MAAcmC,QAAd;;EACA,MAAIF,UAAU,IAAI,IAAlB,EAAwB,MAAMA,UAAN;EACxB,MAAIjC,KAAK,IAAI,IAAb,EAAmB,MAAMA,KAAN;EACnB,SAAOmC,QAAP;EACD;EAWD;EACA;EACA;EACA;EACA;EACA;;;;;;;;;;;;"}
export * from "../dist/index";
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).ReactErrorBoundary={},e.React)}(this,(function(e,r){"use strict";function t(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}})),r.default=e,Object.freeze(r)}var n=t(r);function o(e,r){return o=Object.setPrototypeOf||function(e,r){return e.__proto__=r,e},o(e,r)}var a={error:null},u=function(e){var r,t;function u(){for(var r,t=arguments.length,n=new Array(t),o=0;o<t;o++)n[o]=arguments[o];return(r=e.call.apply(e,[this].concat(n))||this).state=a,r.resetErrorBoundary=function(){for(var e,t=arguments.length,n=new Array(t),o=0;o<t;o++)n[o]=arguments[o];null==r.props.onReset||(e=r.props).onReset.apply(e,n),r.reset()},r}t=e,(r=u).prototype=Object.create(t.prototype),r.prototype.constructor=r,o(r,t),u.getDerivedStateFromError=function(e){return{error:e}};var i=u.prototype;return i.reset=function(){this.setState(a)},i.componentDidCatch=function(e,r){var t,n;null==(t=(n=this.props).onError)||t.call(n,e,r)},i.componentDidUpdate=function(e,r){var t,n,o,a,u=this.state.error,i=this.props.resetKeys;null!==u&&null!==r.error&&(void 0===(o=e.resetKeys)&&(o=[]),void 0===(a=i)&&(a=[]),o.length!==a.length||o.some((function(e,r){return!Object.is(e,a[r])})))&&(null==(t=(n=this.props).onResetKeysChange)||t.call(n,e.resetKeys,i),this.reset())},i.render=function(){var e=this.state.error,r=this.props,t=r.fallbackRender,o=r.FallbackComponent,a=r.fallback;if(null!==e){var u={error:e,resetErrorBoundary:this.resetErrorBoundary};if(n.isValidElement(a))return a;if("function"==typeof t)return t(u);if(o)return n.createElement(o,u);throw new Error("react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop")}return this.props.children},u}(n.Component);e.ErrorBoundary=u,e.useErrorHandler=function(e){var r=n.useState(null),t=r[0],o=r[1];if(null!=e)throw e;if(null!=t)throw t;return o},e.withErrorBoundary=function(e,r){var t=function(t){return n.createElement(u,r,n.createElement(e,t))},o=e.displayName||e.name||"Unknown";return t.displayName="withErrorBoundary("+o+")",t},Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=react-error-boundary.umd.min.js.map
{"version":3,"file":"react-error-boundary.umd.min.js","sources":["../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","../src/index.tsx","../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js"],"sourcesContent":["export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","import * as React from 'react'\n\nconst changedArray = (a: Array<unknown> = [], b: Array<unknown> = []) =>\n a.length !== b.length || a.some((item, index) => !Object.is(item, b[index]))\n\ninterface FallbackProps {\n error: Error\n resetErrorBoundary: (...args: Array<unknown>) => void\n}\n\ninterface ErrorBoundaryPropsWithComponent {\n onResetKeysChange?: (\n prevResetKeys: Array<unknown> | undefined,\n resetKeys: Array<unknown> | undefined,\n ) => void\n onReset?: (...args: Array<unknown>) => void\n onError?: (error: Error, info: {componentStack: string}) => void\n resetKeys?: Array<unknown>\n fallback?: never\n FallbackComponent: React.ComponentType<FallbackProps>\n fallbackRender?: never\n}\n\ndeclare function FallbackRender(\n props: FallbackProps,\n): React.ReactElement<\n unknown,\n string | React.FunctionComponent | typeof React.Component\n> | null\n\ninterface ErrorBoundaryPropsWithRender {\n onResetKeysChange?: (\n prevResetKeys: Array<unknown> | undefined,\n resetKeys: Array<unknown> | undefined,\n ) => void\n onReset?: (...args: Array<unknown>) => void\n onError?: (error: Error, info: {componentStack: string}) => void\n resetKeys?: Array<unknown>\n fallback?: never\n FallbackComponent?: never\n fallbackRender: typeof FallbackRender\n}\n\ninterface ErrorBoundaryPropsWithFallback {\n onResetKeysChange?: (\n prevResetKeys: Array<unknown> | undefined,\n resetKeys: Array<unknown> | undefined,\n ) => void\n onReset?: (...args: Array<unknown>) => void\n onError?: (error: Error, info: {componentStack: string}) => void\n resetKeys?: Array<unknown>\n fallback: React.ReactElement<\n unknown,\n string | React.FunctionComponent | typeof React.Component\n > | null\n FallbackComponent?: never\n fallbackRender?: never\n}\n\ntype ErrorBoundaryProps =\n | ErrorBoundaryPropsWithFallback\n | ErrorBoundaryPropsWithComponent\n | ErrorBoundaryPropsWithRender\n\ntype ErrorBoundaryState = {error: Error | null}\n\nconst initialState: ErrorBoundaryState = {error: null}\n\nclass ErrorBoundary extends React.Component<\n React.PropsWithRef<React.PropsWithChildren<ErrorBoundaryProps>>,\n ErrorBoundaryState\n> {\n static getDerivedStateFromError(error: Error) {\n return {error}\n }\n\n state = initialState\n resetErrorBoundary = (...args: Array<unknown>) => {\n this.props.onReset?.(...args)\n this.reset()\n }\n\n reset() {\n this.setState(initialState)\n }\n\n componentDidCatch(error: Error, info: React.ErrorInfo) {\n this.props.onError?.(error, info)\n }\n\n componentDidUpdate(\n prevProps: ErrorBoundaryProps,\n prevState: ErrorBoundaryState,\n ) {\n const {error} = this.state\n const {resetKeys} = this.props\n\n // There's an edge case where if the thing that triggered the error\n // happens to *also* be in the resetKeys array, we'd end up resetting\n // the error boundary immediately. This would likely trigger a second\n // error to be thrown.\n // So we make sure that we don't check the resetKeys on the first call\n // of cDU after the error is set\n\n if (\n error !== null &&\n prevState.error !== null &&\n changedArray(prevProps.resetKeys, resetKeys)\n ) {\n this.props.onResetKeysChange?.(prevProps.resetKeys, resetKeys)\n this.reset()\n }\n }\n\n render() {\n const {error} = this.state\n\n const {fallbackRender, FallbackComponent, fallback} = this.props\n\n if (error !== null) {\n const props = {\n error,\n resetErrorBoundary: this.resetErrorBoundary,\n }\n if (React.isValidElement(fallback)) {\n return fallback\n } else if (typeof fallbackRender === 'function') {\n return fallbackRender(props)\n } else if (FallbackComponent) {\n return <FallbackComponent {...props} />\n } else {\n throw new Error(\n 'react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop',\n )\n }\n }\n\n return this.props.children\n }\n}\n\nfunction withErrorBoundary<P>(\n Component: React.ComponentType<P>,\n errorBoundaryProps: ErrorBoundaryProps,\n): React.ComponentType<P> {\n const Wrapped: React.ComponentType<P> = props => {\n return (\n <ErrorBoundary {...errorBoundaryProps}>\n <Component {...props} />\n </ErrorBoundary>\n )\n }\n\n // Format for display in DevTools\n const name = Component.displayName || Component.name || 'Unknown'\n Wrapped.displayName = `withErrorBoundary(${name})`\n\n return Wrapped\n}\n\nfunction useErrorHandler(givenError?: unknown): (error: unknown) => void {\n const [error, setError] = React.useState<unknown>(null)\n if (givenError != null) throw givenError\n if (error != null) throw error\n return setError\n}\n\nexport {ErrorBoundary, withErrorBoundary, useErrorHandler}\nexport type {\n FallbackProps,\n ErrorBoundaryPropsWithComponent,\n ErrorBoundaryPropsWithRender,\n ErrorBoundaryPropsWithFallback,\n ErrorBoundaryProps,\n}\n\n/*\neslint\n @typescript-eslint/sort-type-union-intersection-members: \"off\",\n @typescript-eslint/no-throw-literal: \"off\",\n @typescript-eslint/prefer-nullish-coalescing: \"off\"\n*/\n","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}"],"names":["_setPrototypeOf","o","p","Object","setPrototypeOf","__proto__","initialState","error","ErrorBoundary","subClass","superClass","state","resetErrorBoundary","args","props","onReset","reset","prototype","create","constructor","getDerivedStateFromError","setState","componentDidCatch","info","onError","componentDidUpdate","prevProps","prevState","a","b","this","resetKeys","length","some","item","index","is","onResetKeysChange","render","fallbackRender","FallbackComponent","fallback","React","isValidElement","Error","children","Component","givenError","useState","setError","errorBoundaryProps","Wrapped","name","displayName"],"mappings":"ukBAAe,SAASA,EAAgBC,EAAGC,UACzCF,EAAkBG,OAAOC,gBAAkB,SAAyBH,EAAGC,UACrED,EAAEI,UAAYH,EACPD,GAGFD,EAAgBC,EAAGC,GCJ5B,IAgEMI,EAAmC,CAACC,MAAO,MAE3CC,cCnES,IAAw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