Skip to content

Commit 87e7cbe

Browse files
author
Brad Wade
committed
Fix issue #324: Re-using the same dataset in another chart (for example, in tabs) causes a failure.
1 parent b404772 commit 87e7cbe

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

src/index.js

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ class ChartComponent extends React.Component {
5959

6060
componentDidUpdate() {
6161
if (this.props.redraw) {
62-
this.chartInstance.destroy();
62+
this.destroyChart();
6363
this.renderChart();
6464
return;
6565
}
@@ -110,7 +110,7 @@ class ChartComponent extends React.Component {
110110
}
111111

112112
componentWillUnmount() {
113-
this.chartInstance.destroy();
113+
this.destroyChart();
114114
}
115115

116116
transformDataProp(props) {
@@ -143,6 +143,8 @@ class ChartComponent extends React.Component {
143143
})
144144
};
145145

146+
this.saveCurrentDatasets(); // to remove the dataset metadata from this chart when the chart is destroyed
147+
146148
return data;
147149
}
148150

@@ -165,6 +167,18 @@ class ChartComponent extends React.Component {
165167
}
166168
}
167169

170+
getCurrentDatasets() {
171+
return (this.chartInstance && this.chartInstance.config.data && this.chartInstance.config.data.datasets) || [];
172+
}
173+
174+
saveCurrentDatasets() {
175+
this.datasets = this.datasets || {};
176+
var currentDatasets = this.getCurrentDatasets();
177+
currentDatasets.forEach(d => {
178+
this.datasets[this.props.datasetKeyProvider(d)] = d;
179+
})
180+
}
181+
168182
updateChart() {
169183
const {options} = this.props;
170184

@@ -178,7 +192,7 @@ class ChartComponent extends React.Component {
178192

179193
// Pipe datasets to chart instance datasets enabling
180194
// seamless transitions
181-
let currentDatasets = (this.chartInstance.config.data && this.chartInstance.config.data.datasets) || [];
195+
let currentDatasets = this.getCurrentDatasets();
182196
const nextDatasets = data.datasets || [];
183197
this.checkDatasets(currentDatasets);
184198

@@ -239,6 +253,19 @@ class ChartComponent extends React.Component {
239253
});
240254
}
241255

256+
destroyChart() {
257+
// Put all of the datasets that have existed in the chart back on the chart
258+
// so that the metadata associated with this chart get destroyed.
259+
// This allows the datasets to be used in another chart. This can happen,
260+
// for example, in a tabbed UI where the chart gets created each time the
261+
// tab gets switched to the chart and uses the same data).
262+
this.saveCurrentDatasets();
263+
const datasets = Object.values(this.datasets);
264+
this.chartInstance.config.data.datasets = datasets;
265+
266+
this.chartInstance.destroy();
267+
}
268+
242269
handleOnClick = (event) => {
243270
const instance = this.chartInstance;
244271

0 commit comments

Comments
 (0)