Search code examples
reactjsreact-error-boundary

ErrorBoundary not working in functional component with Suspense


I am working with a functional component in which I implemented Lazy loading and compoent is lazy loading fine. But in a sanario while there is no component ErrorBoundary is not working and app is breaking with no fallback UI/msg. My code is

export const SiteContent = () => {
  const [selectedOption, setSelectedOption] = useState(null);

  let LazyLoadedComponent = null;
  if (selectedOption?.component) {
    LazyLoadedComponent = React.lazy(
      () =>
        import(
          `./components/${selectedOption.option.value}/${selectedOption.option.value}`
        )
    );
  }

  return (
    <>
      <ErrorBoundary>
        <Suspense fallback={<div>Loading....</div>}>
          {selectedOption?.component && LazyLoadedComponent && (
            <LazyLoadedComponent />
          )}
        </Suspense>
      </ErrorBoundary>
    </>
  );
};

ErrorBoundary code is

import React from "react";
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, errorInfo) {
    // You can also log the error to an error reporting service
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;


Solution

  • Try setting your hasError state to true in the componentDidCatch method.

    componentDidCatch(error, errorInfo) {
      this.setState({ hasError: true});
    }