I am having a react component that looks something like this. It internally uses highcharts-react to render a chart by fetching a data from an API by supplying the API some of its state properties.
export default class CandlestickChart extends React.Component {
constructor (props) {
super(props);
this.state = {
apiParam1: this.props.propData.param1,
apiParam2: this.props.propData.param2,
chartConfig: this.getChartConfig(this.props.apiParam1),
};
}
componentDidMount() {
this.renderChart();
}
render() {
return (
<div className='col-lg-6'>
<div className='well'>
<ReactHighStock config={this.state.chartConfig} />
</div>
</div>
);
}
renderChart() {
var that = this;
NanoAjax.ajax({
url: 'myApi.com?param1=' + this.state.apiParam1 + '¶m2=' + this.state.apiParam2;
}, function (statusCode, responseText) {
//transform the data a bit
var chartConfig = that.getChartConfig(that.state.apiParam1);
chartConfig.series[0].data = chartData;
that.setState({
chartConfig: chartConfig
})
});
}
getChartConfig(param1) {
// returns HighCharts chartConfig object based on apiParam1
}
}
This works perfectly fine as long as the component is static, i.e., once the params are set during initial render, the parent control will never update it. Also, this approach is same as given in here : https://daveceddia.com/ajax-requests-in-react/
However, my requirement is that, the parent control can update the props param1 and param2 of this control, causing it to make a fresh ajax call with these values and re-render the chart with new data.
How to approach this?
Your solutions renders the chart only when the component has been mounted
componentDidMount() {
this.renderChart();
}
While the requirement is to rerender the chart once param1 and param2 change. For that we could use componentWillReceiveProps, where you'll compare values and act accordingly
componentWillReceiveProps(nextProps) {
let shouldRerenderChart = false;
shouldRerenderChart = shouldRerenderChart || this.props.propData.param1 !== nextProps.propData.param1;
shouldRerenderChart = shouldRerenderChart || this.props.propData.param2 !== nextProps.propData.param2;
if (shouldRerenderChart) {
this.renderChart();
}
}
Also, keep your componentDidMount function, because
React doesn't call componentWillReceiveProps with initial props during mounting.
As an alternative you could use componentDidUpdate with a similar approach.