Generate Error Boundary in TypeScript using ChatGPT
To handle client-side errors we need an Error Boundary.
If our component has an error, we will render the fallback component (some fallback UI for the user to use the app).
Error boundaries are a way to catch errors in the app and display a fallback UI instead of the component tree that crashed.
getDerivedStateFromError
— Update state so the next render will show the fallback UI.
componentDidCatch
— You can also log the error to a reporting service.
import React, { Component, ErrorInfo, ReactNode } from 'react';
interface Props {
children?: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError?: boolean;
}
class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(_: Error): State {
return { hasError: true };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('ErrorBoundary caught an error:', error, errorInfo);
}
render() {
const { hasError } = this.state;
const { children, fallback } = this.props;
if (hasError) {
if ( fallback ) {
return fallback;
} else {
return <h1>Something went wrong.</h1>;
}
}
return children;
}
}
export default ErrorBoundary;
Got the below code explanation from ChatGPT:
This Error Boundary component uses TypeScript to define the Props
and State
interfaces. The Props
interface defines a single required property: children
, which is of type ReactNode
. The State
interface defines three properties: hasError
, which is a boolean indicating whether an error has occurred; error
, which is an optional Error
object that contains information about the error that occurred; and errorInfo
, which is an optional ErrorInfo
object that contains additional information about the error.
The ErrorBoundary
class extends Component
from the react
package and defines a constructor that sets the initial state of hasError
to false
.
The getDerivedStateFromError
method is a static method that is called when an error occurs within the component. It takes in an error object and returns an object that will update the component's state. In this case, it returns an object that sets hasError
to true
and error
to the error
object that was passed in.
The componentDidCatch
method is another lifecycle method that is called when an error occurs within the component. It takes in an error object and an error info object, both of which can be used for logging or reporting purposes. In this example, it logs the error and error info to the console and sets the errorInfo
property on the component's state.
The render
method checks the value of hasError
. If it is true
, the component returns an error message containing the error
message and componentStack
property of the errorInfo
object. Otherwise, it returns the children
prop.
Finally, the ErrorBoundary
component is exported as the default export of the module, so it can be imported and used in other components.