0

I'm trying to handle errors in React.lazy, for that I made the following component to which I pass the load function as parameters:

import React, { useState, useEffect, ReactElement, ComponentType } from 'react';
import { useErrorBoundary } from 'react-error-boundary';

interface DynamicImportWrapperProps {
  importComponent: () => Promise<{ default: ComponentType<any> }>;
}

const DynamicImportWrapper = ({
  importComponent,
}: DynamicImportWrapperProps): ReactElement | null => {
  const [Component, setComponent] = useState<ComponentType<any> | null>(null);
  const { showBoundary } = useErrorBoundary();

  useEffect(() => {
    importComponent()
      .then((module) => setComponent(module.default))
      .catch((error) => {
        error.status = 'IMPORT_FAIL';
        showBoundary(error);
      });
  }, [importComponent]);

  if (Component) {
    return <Component />;
  }

  return null;
};

export default DynamicImportWrapper;

When the import fails the ErrorBoundary is displayed correctly but when the import is successful it gives me an error: Cannot read property of undefined(reading: 'length')

jesusrlm
  • 35
  • 8

0 Answers0