2

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

  1. Loading bunch of components lazily using React.lazy()
  2. Have a Error boundary wrapper above Suspense.
  3. 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

  1. If there is any error that occurred within component (may be null pointer errors or whatever) i need to show the fallback ui.
  2. 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 !.

Vikhyath Maiya
  • 3,122
  • 3
  • 34
  • 68

2 Answers2

0

Check out the live example from React's Error Boundary docs.

You should be able to use the componentStack property on errorInfo to determine where the error originated and conditionally display the fallback UI based on that.

Tim
  • 2,843
  • 13
  • 25
0

you can wrap your Toast lazy component with ErrorBoundary I think you will need to show a fallback anyway for that component, this would behave like an "empty try/catch", so in that case the fallback in your renderComponent() will be strictly outside the lazy errors

guiwme5
  • 712
  • 6
  • 10