I have develop a react app. While browsing, if internet connection is switch off then it show unexpected error, loading chunk failed. Should I handle the network error? Or I should only handle the error of the page and that will be enough? I am using react-router-dom 6.20+
This is obviously not a good user experience and should be handled. React provides an Error Boundary component which allows you to catch errors while rendering your child component tree, and this can be leveraged to render appropriate message to user when network error occurred. Rendered page could also include a retry button.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, info) {
// Example "componentStack":
// in ComponentThatThrows (created by App)
// in ErrorBoundary (created by App)
// in div (created by App)
// in App
// you can log //this into your monitoring dashboard
// logErrorToMyService(error, info.componentStack);
console.log("Error occurred: ", error);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI or
// return this.props.fallback
return <h1>Oops an error occurred. Click <a href="/">here</a> to retry</h1>;
}
return this.props.children;
}
}
You can wrap this component around you main app component
2
Answers
You can write a global hook that listens for network status and gives friendly hints, not the browser’s own network error hints.
This is obviously not a good user experience and should be handled. React provides an Error Boundary component which allows you to catch errors while rendering your child component tree, and this can be leveraged to render appropriate message to user when network error occurred. Rendered page could also include a retry button.
You can wrap this component around you main app component