I am improt a component like this in React application:
<div id="editor" className={styles.editor}>
<React.Suspense fallback={<div>Loading...</div>}>
<CollarCodeEditor projectId={pid.toString()}></CollarCodeEditor>
</React.Suspense>
</div>
today I am facing an error like this:
Unexpected Application Error!
Failed to fetch dynamically imported module: https://tex.poemhub.top/assets/CollarCodeEditor-BHaZ2NgK.js
TypeError: Failed to fetch dynamically imported module: https://tex.poemhub.top/assets/CollarCodeEditor-BHaZ2NgK.js
I think this will happen when the client is stay open for a long time, and the server update the website and make the legacy js missing. when the client request the js the next time. will facing this issue. is it possible to handle this error? when I capture this error, just redirect to home page. I am using vite as the build tool.
In these cases, cached or preloaded files may become outdated, and when the app tries to access them, an error occurs. To handle this error, you can use an Error Boundary to catch the error and refresh the app or redirect the user to the homepage.
import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error("Error captured in ErrorBoundary:", error, info);
}
handleRetry = () => {
this.setState({ hasError: false });
window.location.reload();
};
render() {
if (this.state.hasError) {
return (
<div>
<h2>Unexpected Application Error!</h2>
<button onClick={this.handleRetry}>Reload</button>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
Wrap CollarCodeEditor with ErrorBoundary
import React, { Suspense } from 'react';
import CollarCodeEditor from './CollarCodeEditor';
import ErrorBoundary from './ErrorBoundary';
export default function EditorContainer({ pid }) {
return (
<div id="editor" className={styles.editor}>
<Suspense fallback={<div>loading...</div>}>
<ErrorBoundary>
<CollarCodeEditor projectId={pid.toString()} />
</ErrorBoundary>
</Suspense>
</div>
);
}
I hope it helps you.