I hava a function that load component dynamiclly below:
export const loader = (file: string) => {
let pagePath = file.replace(/^views/, 'pages');
pagePath = pagePath.replace(/\/index$/, '');
const LazyComponent = lazy(
() =>
import(
/* webpackChunkName: "dynamic_page" */ `@/${pagePath}/index.tsx`
),
);
return (
<Suspense fallback={<Loading />}>
<LazyComponent />
</Suspense>
);
};
export const Loader: React.FC<{ path: string }> = ({ path }) => {
return (
<ErrorBoundary>
{loader(path)}
</ErrorBoundary>
);
};
When passed wrong path, dynamic import part throw error:
caught Error: Cannot find module './pages/modules/info/priceConfig/index.tsx'
Why is the error not handled by ErrorBoundary component? And if I want to catch it and return a default component, how?
Why is the error not handled by ErrorBoundary component?
The ErrorBoundary handles errors thrown within the React component tree during rendering, lifecycle methods. It does not catch errors thrown within asynchronous code, such as Promises.
A workaround was suggested here: https://eddiewould.com/2021/28/28/handling-rejected-promises-error-boundary-react/
Solution for your problem:
const LazyComponent = lazy(() =>
import...).catch(
(error) => {
console.error("Component Failed Loading:", error);
return { default: FallbackComponent };
}
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With