UNPKG

react-error-boundary

Version:

Simple reusable React error boundary component

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