I have a question regarding the React.lazy() feature. I developing a feature and i am stuck at a point.
My scenario
I have a set up where i am
- Loading bunch of components lazily using React.lazy()
- Have a Error boundary wrapper above Suspense.
- There is a error fallback ui component (
ErrorFallbackToast
) to show when there is an error.
Which looks something (mock) like this
import React, { Suspense, useEffect, lazy } from 'react';
const Toast = React.lazy(() => import('../Toast'));
const MyComponent = () => {
const renderComponent = () => {
switch (type) {
case TYPE.toast:
return <Toast />;
default:
return null;
}
};
return (
<ErrorBoundary fallback={ErrorFallbackToast} onError={() => {}}>
<Suspense fallback={<></>}>{renderComponent()}</Suspense>
</ErrorBoundary>
);
};
export default MyComponent;
I have a scenario where the fallback ui needs to be shown for particular kind of errors and should not be shown for other. For example
- If there is any error that occurred within component (may be null pointer errors or whatever) i need to show the fallback ui.
- If there is any error occurred because of any React.lazy() error during lazy loading of components (ie chunk load failure, or network error), i should not show the fallbackUI.
The Problem
As of now i am not finding any means to distinguish between the error thrown during React lazy loading vs component runtime errors. Is there any way to achieve what i want ?
I am open to using multiple error boundaries , but since both the errors are thrown at the time of mounting i am not able to achieve whatever i want. Any help would be appreciated. Thanks !.