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);
});
});
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>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With