Skip to content

Commit 3d13c37

Browse files
bdwade100jerairrest
authored andcommitted
Fix issue #324: Re-using the same dataset in another chart (for example, in tabs) causes a failure. (#325)
Looks good!
1 parent 156fc6b commit 3d13c37

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
@@ -58,7 +58,7 @@ class ChartComponent extends React.Component {
5858

5959
componentDidUpdate() {
6060
if (this.props.redraw) {
61-
this.chartInstance.destroy();
61+
this.destroyChart();
6262
this.renderChart();
6363
return;
6464
}
@@ -109,7 +109,7 @@ class ChartComponent extends React.Component {
109109
}
110110

111111
componentWillUnmount() {
112-
this.chartInstance.destroy();
112+
this.destroyChart();
113113
}
114114

115115
transformDataProp(props) {
@@ -142,6 +142,8 @@ class ChartComponent extends React.Component {
142142
})
143143
};
144144

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

@@ -164,6 +166,18 @@ class ChartComponent extends React.Component {
164166
}
165167
}
166168

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

@@ -177,7 +191,7 @@ class ChartComponent extends React.Component {
177191

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

@@ -238,6 +252,19 @@ class ChartComponent extends React.Component {
238252
});
239253
}
240254

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

0 commit comments

Comments
 (0)