Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'useErrorHandler()' in React?

I am looking at the react-error-boundary library from here but I do not understand how to use the useErrorHandler(error?: Error)prop.

So lets say I wrap my app with the error boundary - something like this

import {ErrorBoundary} from 'react-error-boundary';

<ErrorBoundary onError={myErrorHandler}>
  <App />
</ErrorBoundary>

How do I use 'useErrorHandler' to catch errors in the asynchronous code callbacks for example to propagate to ErrorBoundary so I can then use myErrorHandler?

Where is 'useErrorHandler' defined or imported?

I am trying to use this as a catch all error setup - sort of when you add throws excection to the main in java.

async code example:

  ...
  return new Promise(function (resolve, reject) {
      axios({
        ...
      })
        .then((res) => {
          resolve(res);
          // <-- ?
        })
        .catch((err) => {
          reject(err);
        });
    });
like image 855
Edv Beq Avatar asked Feb 02 '26 01:02

Edv Beq


1 Answers

The documentation doesn't make it clear about how to import the useErrorHandler function, but it's part of the API, so you can import in the same way that you import ErrorBoundary.

import { useErrorHandler } from 'react-error-boundary';

E.g.: (based on the documentation)


    import { useErrorHandler } from 'react-error-boundary';
    
    function Greeting() {
      const [greeting, setGreeting] = React.useState(null)
      const handleError = useErrorHandler()
     
      function handleSubmit(event) {
        event.preventDefault()
        const name = event.target.elements.name.value
        fetchGreeting(name).then(
          newGreeting => setGreeting(newGreeting),
          handleError,
        )
      }
     
      return greeting ? (
        <div>{greeting}</div>
      ) : (
        <form onSubmit={handleSubmit}>
          <label>Name</label>
          <input id="name" />
          <button type="submit"}>
            get a greeting
          </button>
        </form>
      )
    }

like image 90
José Coelho Avatar answered Feb 04 '26 14:02

José Coelho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!