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
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;
}
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
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;
}
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.
Child.tsx
const { error } = useFetch()
if (error) {
throw new Error(ErrorType.DataFetch, ErrorMessage.DataFetch)
}
Parent.tsx
<ErrorBoundary
onError={(error) => {
if (error.type === ErrorType.DataFetch) {
saveError(error, new Date())
}
}}
fallback={<ErrorScreen />}
>
<Child />
</ErrorBounday>
ErrorBoundary
means your component (and its parents) will be unmounted and loose their state. You can't easily get out of the error state (retry, timeout, button action etc). – Bergi Commented Jan 2 at 17:54