withErrorBoundary.tsx 890 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import type { ComponentType, ErrorInfo, ReactElement } from 'react';
  2. import { Component } from 'react';
  3. class ErrorBoundary extends Component<
  4. {
  5. children: ReactElement;
  6. fallback: ReactElement;
  7. },
  8. {
  9. hasError: boolean;
  10. }
  11. > {
  12. state = { hasError: false };
  13. static getDerivedStateFromError() {
  14. return { hasError: true };
  15. }
  16. componentDidCatch(error: Error, errorInfo: ErrorInfo) {
  17. console.error(error, errorInfo);
  18. }
  19. render() {
  20. if (this.state.hasError) {
  21. return this.props.fallback;
  22. }
  23. return this.props.children;
  24. }
  25. }
  26. export function withErrorBoundary<T extends Record<string, unknown>>(
  27. Component: ComponentType<T>,
  28. ErrorComponent: ReactElement,
  29. ) {
  30. return function WithErrorBoundary(props: T) {
  31. return (
  32. <ErrorBoundary fallback={ErrorComponent}>
  33. <Component {...props} />
  34. </ErrorBoundary>
  35. );
  36. };
  37. }