Skip to content

Commit 64cde0b

Browse files
author
Sébastien Henau
committed
add fallback property to flare error boundary component
1 parent dfe03af commit 64cde0b

File tree

3 files changed

+41
-6
lines changed

3 files changed

+41
-6
lines changed

packages/react/src/FlareErrorBoundary.ts

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,26 @@ import { Component, ErrorInfo, type PropsWithChildren, type ReactNode } from 're
33

44
import { formatComponentStack } from './format-component-stack';
55

6-
type Props = PropsWithChildren<{
6+
export type FlareErrorBoundaryFallbackProps = {
7+
error: Error;
8+
};
9+
10+
export type FlareErrorBoundaryProps = PropsWithChildren<{
11+
fallback?: ReactNode | ((props: FlareErrorBoundaryFallbackProps) => ReactNode);
712
onError?: (error: Error, errorInfo: ErrorInfo) => void;
813
}>;
914

10-
type State = {};
15+
export type FlareErrorBoundaryState = {
16+
error: Error | null;
17+
};
18+
19+
export class FlareErrorBoundary extends Component<FlareErrorBoundaryProps, FlareErrorBoundaryState> {
20+
state: FlareErrorBoundaryState = { error: null };
21+
22+
static getDerivedStateFromError(error: Error): FlareErrorBoundaryState {
23+
return { error };
24+
}
1125

12-
export class FlareErrorBoundary extends Component<Props, State> {
1326
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
1427
const context = {
1528
react: {
@@ -22,7 +35,21 @@ export class FlareErrorBoundary extends Component<Props, State> {
2235
this.props.onError?.(error, errorInfo);
2336
}
2437

25-
render(): ReactNode {
38+
render() {
39+
const { error } = this.state;
40+
41+
if (error !== null) {
42+
const { fallback } = this.props;
43+
44+
if (typeof fallback === 'function') {
45+
return fallback({
46+
error,
47+
});
48+
}
49+
50+
return fallback ?? null;
51+
}
52+
2653
return this.props.children;
2754
}
2855
}

packages/react/src/index.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,6 @@
1-
export { FlareErrorBoundary } from './FlareErrorBoundary';
1+
export {
2+
FlareErrorBoundary,
3+
type FlareErrorBoundaryProps,
4+
type FlareErrorBoundaryFallbackProps,
5+
type FlareErrorBoundaryState,
6+
} from './FlareErrorBoundary';

playground/react/App.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,10 @@ export function App() {
2828
Reset render error
2929
</Button>
3030
{showBuggy && (
31-
<FlareErrorBoundary onError={() => console.log('FlareErrorBoundary onError callback')}>
31+
<FlareErrorBoundary
32+
onError={() => console.log('FlareErrorBoundary onError callback')}
33+
fallback={({ error }) => <p>There has been an error: {error.message}</p>}
34+
>
3235
<BuggyComponent />
3336
</FlareErrorBoundary>
3437
)}

0 commit comments

Comments
 (0)