Skip to content

Commit

Permalink
feat: add TypeScript types for ErrorBoundary and ErrorBoundaryContext
Browse files Browse the repository at this point in the history
  • Loading branch information
Tresau committed Dec 7, 2023
1 parent 670dffc commit 49c2d00
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import React from 'react';
import React, { ErrorInfo, ReactNode } from 'react';
import PropTypes from 'prop-types';
import { ErrorBoundaryContext } from './ErrorBoundaryContext';

Expand All @@ -26,29 +26,39 @@ import { ErrorBoundaryContext } from './ErrorBoundaryContext';
* Reference:
* https://reactjs.org/docs/error-boundaries.html#introducing-error-boundaries
*/
export default class ErrorBoundary extends React.Component {
interface ErrorBoundaryProps {
children?: ReactNode;
fallback?: ReactNode;
}

interface ErrorBoundaryState {
hasError: boolean;
}

export default class ErrorBoundary extends React.Component<ErrorBoundaryProps> {
static propTypes = {
children: PropTypes.node,
fallback: PropTypes.node,
};

static contextType = ErrorBoundaryContext;
context!: React.ContextType<typeof ErrorBoundaryContext>;

static getDerivedStateFromError() {
static getDerivedStateFromError(): ErrorBoundaryState {
return {
hasError: true,
};
}

state = {
state: ErrorBoundaryState = {
hasError: false,
};

componentDidCatch(error, info) {
componentDidCatch(error: Error, info: ErrorInfo) {
this.context.log(error, info);
}

componentDidUpdate(prevProps) {
componentDidUpdate(prevProps: ErrorBoundaryProps) {
if (prevProps.children !== this.props.children) {
this.setState({ hasError: false });
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@
* LICENSE file in the root directory of this source tree.
*/

import { createContext } from 'react';
import { ErrorInfo, createContext } from 'react';

export const ErrorBoundaryContext = createContext({
export interface ErrorBoundaryContextType {
log: (error: Error, errorInfo: ErrorInfo) => void;
}

export const ErrorBoundaryContext = createContext<ErrorBoundaryContextType>({
log(error, info) {
console.log(info.componentStack);
},
Expand Down

0 comments on commit 49c2d00

Please sign in to comment.