I had a react question design that is really just me trying to learn better.
If i have a parent component that is wrapped in a fallback (Error boundary) and you have some api call (I am using a useFetch) and it has an error, is there some use case on
- Rendering an error component when error is truthy
or - throw an exception which will be caught by the ErrorBoundary wrapped around the compoonent and will also render the same fallback component
Both work if i am correct but not sure if there is a better practice reason to pick one over the other
Here is some code examples
component example
<ErrorBoundary fallback={<Fallback />}>
<Parent />
</ErrorBoundary>
method 1
const { loading, error, data = [] } = useFetch('<URL HERE>', options, [])
if (error) {
return (
<Fallback />
)
}
method 2
const { loading, error, data = [] } = useFetch('<URL HERE>', options, [])
if (error) {
throw error;
}
2
Answers
Both approaches work but here are some considerations for when to use each:
Method 1: Error Component
When to use:
Method 2: Throw Exception
When to use:
Advantages:
Disadvantages:
You want to use Method 1 if the error only impacts the current component and you want to display a specific error message and method 2 if the error impacts multiple components or is critical, and you want to rely on the
ErrorBoundary
for consistency.I’d generally recommend Method 2. Hope this helps
error
is not an error, but a boolean.ErrorBoundary
makes sure no surreptitious error leaks to the end user.What you can do in most cases is to catch the boolean and throw an error (with the type and message you like) for consequent modal, redirections or monitoring.