Skip to content

Instantly share code, notes, and snippets.

@rmarscher
Last active October 24, 2024 21:11
Show Gist options
  • Save rmarscher/70aa76af4e5f8db26473bf50e220fb99 to your computer and use it in GitHub Desktop.
Save rmarscher/70aa76af4e5f8db26473bf50e220fb99 to your computer and use it in GitHub Desktop.
React 19 / Waku Error Boundary
"use client";
// import { isDevelopment } from "#is-development";
import type {
ComponentType,
ErrorInfo,
PropsWithChildren,
ReactNode,
} from "react";
import { Component, createContext, createElement } from "react";
declare function FallbackRender(props: FallbackProps): ReactNode;
export type FallbackProps = {
error: any;
resetErrorBoundary: (...args: any[]) => void;
};
type ErrorBoundarySharedProps = PropsWithChildren<{
onError?: (error: Error, info: ErrorInfo) => void;
onReset?: (
details:
| { reason: "imperative-api"; args: any[] }
| { reason: "keys"; prev: any[] | undefined; next: any[] | undefined },
) => void;
resetKeys?: any[];
}>;
export type ErrorBoundaryPropsWithComponent = ErrorBoundarySharedProps & {
fallback?: never;
FallbackComponent: ComponentType<FallbackProps>;
fallbackRender?: never;
};
export type ErrorBoundaryPropsWithRender = ErrorBoundarySharedProps & {
fallback?: never;
FallbackComponent?: never;
fallbackRender: typeof FallbackRender;
};
export type ErrorBoundaryPropsWithFallback = ErrorBoundarySharedProps & {
fallback: ReactNode;
FallbackComponent?: never;
fallbackRender?: never;
};
export type ErrorBoundaryProps =
| ErrorBoundaryPropsWithFallback
| ErrorBoundaryPropsWithComponent
| ErrorBoundaryPropsWithRender;
type ErrorBoundaryState =
| {
didCatch: true;
error: any;
}
| {
didCatch: false;
error: null;
};
export type ErrorBoundaryContextType = {
didCatch: boolean;
error: any;
resetErrorBoundary: (...args: any[]) => void;
};
export const ErrorBoundaryContext =
createContext<ErrorBoundaryContextType | null>(null);
const initialState: ErrorBoundaryState = {
didCatch: false,
error: null,
};
export class ErrorBoundary extends Component<
ErrorBoundaryProps,
ErrorBoundaryState
> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.resetErrorBoundary = this.resetErrorBoundary.bind(this);
this.state = initialState;
}
static getDerivedStateFromError(error: Error) {
return { didCatch: true, error };
}
resetErrorBoundary(...args: any[]) {
const { error } = this.state;
if (error !== null) {
this.props.onReset?.({
args,
reason: "imperative-api",
});
this.setState(initialState);
}
}
componentDidCatch(error: Error, info: ErrorInfo) {
this.props.onError?.(error, info);
}
componentDidUpdate(
prevProps: ErrorBoundaryProps,
prevState: ErrorBoundaryState,
) {
const { didCatch } = 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 (
didCatch &&
prevState.error !== null &&
hasArrayChanged(prevProps.resetKeys, resetKeys)
) {
this.props.onReset?.({
next: resetKeys,
prev: prevProps.resetKeys,
reason: "keys",
});
this.setState(initialState);
}
}
render() {
const { children, fallbackRender, FallbackComponent, fallback } =
this.props;
const { didCatch, error } = this.state;
let childToRender = children;
if (didCatch) {
const props: FallbackProps = {
error,
resetErrorBoundary: this.resetErrorBoundary,
};
if (typeof fallbackRender === "function") {
childToRender = fallbackRender(props);
} else if (FallbackComponent) {
childToRender = createElement(FallbackComponent, props);
} else if (fallback !== undefined) {
childToRender = fallback;
} else {
console.error(
"react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop",
);
throw error;
}
}
return createElement(
ErrorBoundaryContext,
{
value: {
didCatch,
error,
resetErrorBoundary: this.resetErrorBoundary,
},
},
childToRender,
);
}
}
function hasArrayChanged(a: any[] = [], b: any[] = []) {
return (
a.length !== b.length || a.some((item, index) => !Object.is(item, b[index]))
);
}
export default ErrorBoundary;
https://github.com/bvaughn/react-error-boundary/blob/master/LICENSE
The MIT License (MIT)
Copyright (c) 2020 Brian Vaughn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@rmarscher
Copy link
Author

Workaround for wakujs/waku#982

@rmarscher
Copy link
Author

This is basically copying https://github.com/bvaughn/react-error-boundary/blob/master/src/ErrorBoundary.ts and related components to a single file for easy of copy/paste.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment