reactjsreact-error-boundary

reset error boundary on back journey using useErrorHandler hook from react-error-boundary


I am using react-error-boundary package to show the fall back UI in case application throws any errors. The package works fine for me. I need to understand how to reset application error state if I go to previous pages using browser back button as going to previous pages also shows the fall back UI instead of original component. Is there anyway we can render the original component?

In below code user will be thrown error on Page2 since I am passing empty object as props. It will show fallback screen in that case. If I click on back button still fallback screen will be shown on Page1 as well which I don't want.

App.js

const errorHandler = (error) =>{
      console.log(error)
}

<BrowserRouter basename={'/bookingtool/obt/'}>
     <ErrorBoundary FallbackComponent={Fallback} onError={errorHandler}>
          <Routes>
               <Route path="/page1" element={<Page1 PageName="Page1" />} />
               <Route path="/page2" element={<Page2 PageName={{}} /> } />
          </Routes>
    <ErrorBoundary />
</BrowserRouter>

Page1.js

import { useErrorHandler } from 'react-error-boundary';
const Page1 = ({PageName}) =>{
     return(<p>{PageName}</p>)
}

Page2.js

import { useErrorHandler } from 'react-error-boundary';
const Page2 = ({PageName}) =>{
     return(<p>{PageName}</p>)
}

Fallback.js

import React from "react";

const Fallback= (props) => {
    return(<h1>Something went wrong</h1>)
}

Solution

  • Provide a key to <ErrorBoundary />. Whenever the key changes, the error boundary is reset.

    In your case, using useLocation().pathname as key means it will reset whenever the path changes:

    const location =  useLocation();
    
    // ...
    return (
      <ErrorBoundary key={location.pathname}>
        {/* ... */}
      </ErrorBoundary>
    )
    

    As a separate suggestion, I'd move the error handling inside a Layout component. This would allow keeping the navigation when an error happens, which is good UX.

    A basic example here.