Skip to content

Commit

Permalink
feat: add TypeScript types for ErrorBoundary and ErrorBoundaryContext (
Browse files Browse the repository at this point in the history
…#15348)

Co-authored-by: Taylor Jones <tay1orjones@users.noreply.github.com>
  • Loading branch information
Tresau and tay1orjones committed Dec 19, 2023
1 parent d1215c3 commit a0fd477
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 8 deletions.
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
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 a0fd477

Please sign in to comment.