javascript - AJAX requests from a React component -
i having react component looks this. internally uses highcharts-react render chart fetching data api supplying api of 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 = this; nanoajax.ajax({ url: 'myapi.com?param1=' + this.state.apiparam1 + '¶m2=' + this.state.apiparam2; }, function (statuscode, responsetext) { //transform data 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 fine long component static, i.e., once params set during initial render, parent control never update it. also, approach same given in here : https://daveceddia.com/ajax-requests-in-react/
however, requirement that, parent control can update props param1
, param2
of control, causing make fresh ajax call these values , re-render chart new data.
how approach this?
your solutions renders chart when component has been mounted
componentdidmount() { this.renderchart(); }
while requirement rerender chart once param1
, param2
change. use componentwillreceiveprops, you'll compare values , 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 componentdidmount function, because
react doesn't call componentwillreceiveprops initial props during mounting.
as alternative use componentdidupdate similar approach.
Comments
Post a Comment