UNPKG

react-error-boundary

Version:

Simple reusable React error boundary component

3 lines (2 loc) 2.1 kB
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react"),c=s.createContext(null),u={didCatch:!1,error:null};class l extends s.Component{constructor(e){super(e),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=u}static getDerivedStateFromError(e){return{didCatch:!0,error:e}}resetErrorBoundary(...e){const{error:t}=this.state;t!==null&&(this.props.onReset?.({args:e,reason:"imperative-api"}),this.setState(u))}componentDidCatch(e,t){this.props.onError?.(e,t)}componentDidUpdate(e,t){const{didCatch:o}=this.state,{resetKeys:n}=this.props;o&&t.error!==null&&y(e.resetKeys,n)&&(this.props.onReset?.({next:n,prev:e.resetKeys,reason:"keys"}),this.setState(u))}render(){const{children:e,fallbackRender:t,FallbackComponent:o,fallback:n}=this.props,{didCatch:a,error:i}=this.state;let d=e;if(a){const h={error:i,resetErrorBoundary:this.resetErrorBoundary};if(typeof t=="function")d=t(h);else if(o)d=s.createElement(o,h);else if(n!==void 0)d=n;else throw i}return s.createElement(c.Provider,{value:{didCatch:a,error:i,resetErrorBoundary:this.resetErrorBoundary}},d)}}function y(r=[],e=[]){return r.length!==e.length||r.some((t,o)=>!Object.is(t,e[o]))}function E(r){return r!==null&&typeof r=="object"&&"didCatch"in r&&typeof r.didCatch=="boolean"&&"error"in r&&"resetErrorBoundary"in r&&typeof r.resetErrorBoundary=="function"}function f(r){if(!E(r))throw new Error("ErrorBoundaryContext not found")}function p(){const r=s.useContext(c);f(r);const{error:e,resetErrorBoundary:t}=r,[o,n]=s.useState({error:null,hasError:!1}),a=s.useMemo(()=>({error:e,resetBoundary:()=>{t(),n({error:null,hasError:!1})},showBoundary:i=>n({error:i,hasError:!0})}),[e,t]);if(o.hasError)throw o.error;return a}function B(r,e){const t=s.forwardRef((n,a)=>s.createElement(l,e,s.createElement(r,{...n,ref:a}))),o=r.displayName||r.name||"Unknown";return t.displayName=`withErrorBoundary(${o})`,t}exports.ErrorBoundary=l;exports.ErrorBoundaryContext=c;exports.useErrorBoundary=p;exports.withErrorBoundary=B; //# sourceMappingURL=react-error-boundary.cjs.map