16
16
* specific language governing permissions and limitations
17
17
* under the License.
18
18
*/
19
- import React , { createRef , useEffect , useState } from 'react' ;
19
+ import React , { useRef , useEffect } from 'react' ;
20
20
import styled from '@superset-ui/style' ;
21
21
import echarts from 'echarts' ;
22
22
import { EchartsProps , EchartsStylesProps } from '../types' ;
@@ -26,38 +26,23 @@ const Styles = styled.div<EchartsStylesProps>`
26
26
width: ${ ( { width } ) => width } ;
27
27
` ;
28
28
29
- export default function Echart ( props : EchartsProps ) {
30
- const { height, width, echartOptions } = props ;
31
- const [ rootElem , setRootElem ] = useState ( { obj : undefined } as {
32
- obj ?: React . RefObject < HTMLDivElement > ;
33
- } ) ;
34
- const [ chart , setChart ] = useState ( { obj : undefined } as { obj ?: echarts . ECharts } ) ;
29
+ export default function Echart ( { width, height, echartOptions } : EchartsProps ) {
30
+ const divRef = useRef < HTMLDivElement > ( ) ;
31
+ const chartRef = useRef < echarts . ECharts > ( ) ;
35
32
36
33
useEffect ( ( ) => {
37
- setRootElem ( { obj : createRef < HTMLDivElement > ( ) } ) ;
38
- } , [ ] ) ;
39
-
40
- useEffect ( ( ) => {
41
- if ( rootElem . obj ) {
42
- const root = rootElem . obj . current as HTMLDivElement ;
43
- setChart ( { obj : echarts . init ( root ) } ) ;
44
- }
45
- } , [ rootElem ] ) ;
46
-
47
- useEffect ( ( ) => {
48
- if ( chart . obj ) {
49
- chart . obj . setOption ( echartOptions , true ) ;
34
+ if ( ! divRef . current ) return ;
35
+ if ( ! chartRef . current ) {
36
+ chartRef . current = echarts . init ( divRef . current ) ;
50
37
}
51
- } , [ chart , echartOptions ] ) ;
38
+ chartRef . current . setOption ( echartOptions , true ) ;
39
+ } , [ echartOptions ] ) ;
52
40
53
41
useEffect ( ( ) => {
54
- if ( chart . obj ) {
55
- chart . obj . resize ( {
56
- width,
57
- height,
58
- } ) ;
42
+ if ( chartRef . current ) {
43
+ chartRef . current . resize ( { width, height } ) ;
59
44
}
60
- } , [ chart , width , height ] ) ;
45
+ } , [ width , height ] ) ;
61
46
62
- return < Styles ref = { rootElem . obj } height = { height } width = { width } /> ;
47
+ return < Styles ref = { divRef } height = { height } width = { width } /> ;
63
48
}
0 commit comments