import React from 'react' interface FallbackProps { error: Error; resetErrorBoundary: (...args: Array) => void; } interface ErrorBoundaryProps { onResetKeysChange?: ( prevResetKeys: Array | undefined, resetKeys: Array | undefined ) => void; onReset?: (...args: Array) => void; onError?: (error: Error, info: { componentStack: string }) => void; resetKeys?: Array; fallback: React.ComponentType; } interface ErrorBoundaryState { error: Error | null } const changedArray = (a: Array = [], b: Array = []) => ( a.length !== b.length || a.some((item, index) => !Object.is(item, b[index])) ) const initialState: ErrorBoundaryState = { error: null } export default class ErrorBoundary extends React.Component< React.PropsWithRef>, ErrorBoundaryState > { static getDerivedStateFromError(error: Error) { return { error } } state = initialState updatedWithError = false componentDidMount() { const { error } = this.state if (error !== null) { this.updatedWithError = true } } componentDidUpdate(prevProps: ErrorBoundaryProps) { const { error } = this.state const { resetKeys } = this.props // There's an edge case where if the thing that triggered the error // happens to *also* be in the resetKeys array, we'd end up resetting // the error boundary immediately. This would likely trigger a second // error to be thrown. // So we make sure that we don't check the resetKeys on the first call // of cDU after the error is set if (error !== null && !this.updatedWithError) { this.updatedWithError = true return } if (error !== null && changedArray(prevProps.resetKeys, resetKeys)) { this.props.onResetKeysChange?.(prevProps.resetKeys, resetKeys) this.reset() } } componentDidCatch(error: Error, info: React.ErrorInfo) { this.props.onError?.(error, info) } resetErrorBoundary = (...args: Array) => { this.props.onReset?.(...args) this.reset() } reset() { this.updatedWithError = false this.setState(initialState) } render() { const { error } = this.state const { fallback: Fallback } = this.props if (error !== null) { const props = { error, resetErrorBoundary: this.resetErrorBoundary, } return } return this.props.children } }