Ashwani Panwar
Ashwani Panwar

Reputation: 4578

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;

Upvotes: 0

Views: 4243

Answers (2)

ivanatias
ivanatias

Reputation: 4033

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

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

Upvotes: 1

nullptr
nullptr

Reputation: 4484

You have to set the hasError state to true for the fallback UI to be shown.

Change your ErrorBoundary's componentDidCatch to :

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

Upvotes: 1

Related Questions