react-error-boundary
Version:
Simple reusable React error boundary component
3 lines (2 loc) • 2.27 kB
JavaScript
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react"),u=s.createContext(null),c={didCatch:!1,error:null};class h extends s.Component{constructor(e){super(e),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=c}static getDerivedStateFromError(e){return{didCatch:!0,error:e}}resetErrorBoundary(...e){const{didCatch:t}=this.state;t&&(this.props.onReset?.({args:e,reason:"imperative-api"}),this.setState(c))}componentDidCatch(e,t){this.props.onError?.(e,t)}componentDidUpdate(e,t){const{didCatch:o}=this.state,{resetKeys:n}=this.props;o&&t.didCatch&&l(e.resetKeys,n)&&(this.props.onReset?.({next:n,prev:e.resetKeys,reason:"keys"}),this.setState(c))}render(){const{children:e,fallbackRender:t,FallbackComponent:o,fallback:n}=this.props,{didCatch:a,error:i}=this.state;let d=e;if(a){const y={error:i,resetErrorBoundary:this.resetErrorBoundary};if(typeof t=="function")d=t(y);else if(o)d=s.createElement(o,y);else if(n!==void 0)d=n;else throw i}return s.createElement(u.Provider,{value:{didCatch:a,error:i,resetErrorBoundary:this.resetErrorBoundary}},d)}}function l(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(u);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){switch(typeof r){case"object":{if(r!==null&&"message"in r&&typeof r.message=="string")return r.message;break}case"string":return r}}function m(r,e){const t=s.forwardRef((n,a)=>s.createElement(h,e,s.createElement(r,{...n,ref:a}))),o=r.displayName||r.name||"Unknown";return t.displayName=`withErrorBoundary(${o})`,t}exports.ErrorBoundary=h;exports.ErrorBoundaryContext=u;exports.getErrorMessage=B;exports.useErrorBoundary=p;exports.withErrorBoundary=m;
//# sourceMappingURL=react-error-boundary.cjs.map