When should we use Error Boundary components? Only for missing props and stuff like that?
For example, imagine this api fetching hook:
const useFetch = () => {
...
const [error, setError] = useState(null);
const method = async () => {
try {
await api.fetchData();
} catch(err) {
setError(err);
}
};
useEffect(() => {
method();
},[]);
return { ..., error };
}
Now, in a component, I just do:
const MyComponent = () => {
const { error } = useFetch();
if (error) return <FallbackUI />;
return <MainUI />;
}
Can I use an ErrorBoundary component to handle this situation (api call errors) instead of conditionally rendering?
And what about if I only want to display a fallback UI when my fetching data method fails and there any data was previously retrieved?
Something like:
const { data, getMoreData, error } = useFetchPosts(); // data is stateful inside the hook
if (error && !data) return <FallbackUI />;
return <MainUI data={data} />;
I've followed the following approach in my projects that are all hooks/functional component implementations.
I'm using https://github.com/bvaughn/react-error-boundary
import { ErrorBoundary } from "react-error-boundary";
<ErrorBoundary FallbackComponent={ErrorFallback}>
<MyComponent />
</ErrorBoundary>
//reject the promise so it gets bubbled up
const useFetch = () => {
...
const [error, setError] = useState(null);
const method = async () => {
try {
await api.fetchData();
} catch(err) {
// setError(err);
return Promise.reject(err);
}
};
useEffect(() => {
method();
},[]);
return { ..., error };
}
function ErrorFallback({ error }: { error: any }) {
return (
<>
// you custom ui you'd like to return
</>
);
}
EDIT:
I typically have this at the top level so this is typically a catch all for all the unhandled exceptions. In other words, I wrap my App.tsx in the root index.tsx file in an ErrorBoundary. So, my code looks more like this
...
<ErrorBoundary FallbackComponent={ErrorFallback}>
<SWRConfig ...>
<React.StrictMode>
<ScrollToTop></ScrollToTop>
<App ... />
</React.StrictMode>
</SWRConfig>
</ErrorBoundary>