Skip to content

Commit bcd940d

Browse files
authored
Allow data pass as function that receive ctx
1 parent 5c826af commit bcd940d

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

src/index.js

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ import isEqual from 'lodash.isequal';
55

66
class ChartComponent extends React.Component {
77
static propTypes = {
8-
data: PropTypes.object.isRequired,
8+
data: PropTypes.oneOfType([
9+
PropTypes.object,
10+
PropTypes.func
11+
]).isRequired,
912
getDatasetAtEvent: PropTypes.func,
1013
getElementAtEvent: PropTypes.func,
1114
getElementsAtEvent: PropTypes.func,
@@ -78,34 +81,45 @@ class ChartComponent extends React.Component {
7881
return true;
7982
}
8083

81-
return !isEqual(this.shadowDataProp, nextProps.data);
84+
const nextData = this.transformDataProp()
85+
return !isEqual(this.shadowDataProp, nextData);
8286
}
8387

8488
componentWillUnmount() {
8589
this.chart_instance.destroy();
8690
}
8791

92+
transformDataProp() {
93+
const { dataProp } = this.props;
94+
const node = ReactDOM.findDOMNode(this);
95+
return (typeof(dataProp) == "function") ? dataProp(node) : dataProp;
96+
}
97+
8898
// Chart.js directly mutates the data.dataset objects by adding _meta proprerty
8999
// this makes impossible to compare the current and next data changes
90100
// therefore we memoize the data prop while sending a fake to Chart.js for mutation.
91101
// see https://github.com/chartjs/Chart.js/blob/master/src/core/core.controller.js#L615-L617
92102
memoizeDataProps() {
93-
const { data } = this.props;
103+
const { dataProp } = this.props;
94104

95-
if (!data) {
105+
if (!dataProp) {
96106
return;
97107
}
98108

109+
const data = this.transformDataProp();
110+
99111
this.shadowDataProp = {
100112
...data,
101113
datasets: data.datasets && data.datasets.map(set => Object.assign({}, set))
102114
};
115+
116+
return data;
103117
}
104118

105119
updateChart() {
106-
const {data, options} = this.props;
120+
const {options} = this.props;
107121

108-
this.memoizeDataProps();
122+
const data = this.memoizeDataProps();
109123

110124
if (!this.chart_instance) return;
111125

@@ -154,10 +168,10 @@ class ChartComponent extends React.Component {
154168
}
155169

156170
renderChart() {
157-
const {data, options, legend, type, redraw} = this.props;
171+
const {options, legend, type, redraw} = this.props;
158172
const node = ReactDOM.findDOMNode(this);
159173

160-
this.memoizeDataProps();
174+
const data = this.memoizeDataProps();
161175

162176
this.chart_instance = new Chart(node, {
163177
type,

0 commit comments

Comments
 (0)