Skip to content

Commit 77427eb

Browse files
fix(Charts): use ErrorBoundary to prevent errors when components are re-mounted (#1190)
fixes #1145
1 parent 754050a commit 77427eb

1 file changed

Lines changed: 26 additions & 4 deletions

File tree

packages/charts/src/internal/ChartContainer.tsx

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@ import { createComponentStyles } from '@ui5/webcomponents-react-base/lib/createC
22
import { ThemingParameters } from '@ui5/webcomponents-react-base/lib/ThemingParameters';
33
import { usePassThroughHtmlProps } from '@ui5/webcomponents-react-base/lib/usePassThroughHtmlProps';
44
import { CommonProps } from '@ui5/webcomponents-react/interfaces/CommonProps';
5+
import { Label } from '@ui5/webcomponents-react/lib/Label';
56
import { Loader } from '@ui5/webcomponents-react/lib/Loader';
6-
import React, { ComponentType, CSSProperties, FC, forwardRef, ReactElement, Ref, useMemo } from 'react';
7+
import React, { ComponentType, CSSProperties, FC, forwardRef, ReactElement, ReactNode, Ref, useMemo } from 'react';
78
import { ResponsiveContainer } from 'recharts';
89

910
export interface ContainerProps extends CommonProps {
@@ -41,6 +42,25 @@ const chartContainerStyles = {
4142

4243
const useStyles = createComponentStyles(chartContainerStyles, { name: 'ChartContainer' });
4344

45+
class ErrorBoundary extends React.Component<{ children: ReactNode }, { errorCount: number }> {
46+
state = {
47+
errorCount: 0
48+
};
49+
50+
componentDidCatch() {
51+
if (this.state.errorCount < 3) {
52+
this.setState((old) => ({ ...old, errorCount: old.errorCount + 1 }));
53+
}
54+
}
55+
56+
render() {
57+
if (this.state.errorCount >= 3) {
58+
return <Label>Sorry, something went wrong while rendering this chart!</Label>;
59+
}
60+
return this.props.children;
61+
}
62+
}
63+
4464
const ChartContainer: FC<ContainerProps> = forwardRef((props: ContainerProps, ref: Ref<any>) => {
4565
const { Placeholder, loading = false, dataset, style, className, tooltip, slot, children, resizeDebounce } = props;
4666
useStyles();
@@ -65,9 +85,11 @@ const ChartContainer: FC<ContainerProps> = forwardRef((props: ContainerProps, re
6585
<>
6686
{loading && <Loader style={loaderStyles} />}
6787
{
68-
<ResponsiveContainer debounce={resizeDebounce} {...__testingProps__}>
69-
{children}
70-
</ResponsiveContainer>
88+
<ErrorBoundary>
89+
<ResponsiveContainer debounce={resizeDebounce} {...__testingProps__}>
90+
{children}
91+
</ResponsiveContainer>
92+
</ErrorBoundary>
7193
}
7294
</>
7395
) : (

0 commit comments

Comments
 (0)