UNPKG

@royaltics/tracker-react

Version:

React hooks for Royaltics Error Tracker

2 lines (1 loc) 2.15 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),s=require("react"),l=require("@royaltics/tracker"),i=s.createContext(null),d=()=>{const r=s.useContext(i);if(!r)throw new Error("useErrorTrackerContext must be used within ErrorTrackerProvider");return r},C=({config:r,children:e})=>{const t=s.useRef(null);return s.useEffect(()=>(t.current||(t.current=l.Tracker.create({...r,platform:"react",app:"react-app"})),()=>{t.current&&(l.Tracker.shutdown(),t.current=null)}),[r]),t.current?a.jsx(i.Provider,{value:t.current,children:e}):a.jsx(a.Fragment,{children:e})};class E extends s.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e instanceof Error?e:new Error(String(e??"Unknown error"))}}componentDidCatch(e,t){try{const c=e instanceof Error?e:new Error(String(e??"Unknown error"));this.props.client.error(c,"ERROR",{componentStack:t.componentStack,source:"ErrorBoundary"})}catch(c){console.error("Failed to track error:",c)}}render(){return this.state.hasError&&this.state.error?this.props.fallback?typeof this.props.fallback=="function"?this.props.fallback(this.state.error):this.props.fallback:a.jsxs("div",{style:{padding:"20px",textAlign:"center"},children:[a.jsx("h1",{children:"Something went wrong"}),a.jsx("p",{children:this.state.error.message})]}):this.props.children}}const b=()=>{const r=d(),e=s.useCallback((o,n)=>{r.error(o,"ERROR",n)},[r]),t=s.useCallback((o,n)=>{r.error(o,"FATAL",n)},[r]),c=s.useCallback((o,n)=>{r.error(o,"DEBUG",n)},[r]),p=s.useCallback((o,n,u)=>{r.error(o,n,u)},[r]),k=s.useCallback((o,n)=>{r.event(o,"INFO",n)},[r]),h=s.useCallback((o,n)=>{r.event(o,"WARNING",n)},[r]),f=s.useCallback((o,n,u)=>{r.event(o,n,u)},[r]),m=s.useCallback(async()=>{await r.forceFlush()},[r]);return{error:e,fatal:t,debug:c,capture:p,info:k,warn:h,event:f,flush:m}},x=()=>{const r=d();return{ErrorBoundary:({children:t,fallback:c})=>a.jsx(E,{client:r,fallback:c,children:t})}};exports.ErrorBoundary=E;exports.ErrorTrackerProvider=C;exports.useErrorBoundary=x;exports.useErrorTracker=b;