diff --git a/src/components/ErrorBoundary.jsx b/src/components/ErrorBoundary.jsx new file mode 100644 index 0000000..e54e5ac --- /dev/null +++ b/src/components/ErrorBoundary.jsx @@ -0,0 +1,34 @@ +import React from "react"; + +export class ErrorBoundary extends React.Component { + constructor(props) { + super(props); + this.state = { hasError: false }; + } + + static getDerivedStateFromError(error) { + // Update state so the next render will show the fallback UI. + return { hasError: true }; + } + + componentDidCatch(error, info) { + // Example "componentStack": + // in ComponentThatThrows (created by App) + // in ErrorBoundary (created by App) + // in div (created by App) + // in App + // logErrorToMyService(error, info.componentStack); + + console.log(error); + console.log(info.componentStack); + } + + render() { + if (this.state.hasError) { + // You can render any custom fallback UI + return this.props.fallback; + } + + return this.props.children; + } +} diff --git a/src/index.js b/src/index.js index 775fa6f..1b3f007 100644 --- a/src/index.js +++ b/src/index.js @@ -7,6 +7,7 @@ import { BrowserRouter, Route, Routes, useLocation } from "react-router-dom"; import { AnimatePresence } from "framer-motion"; import Home from "./pages/Home.jsx"; import Profile from "./pages/Profile.jsx"; +import {ErrorBoundary} from "./components/ErrorBoundary.jsx"; const root = ReactDOM.createRoot(document.getElementById("root")); @@ -14,7 +15,9 @@ root.render( - + Something went wrong

}> + +