javascript - React: Event-triggered Ajax call in componentDidUpdate or render creates infinite loop -
i have ajax call triggered event(click). works it's supposed to(it populate table), keeps doing ajax call time, eating out memory unsustainable, of course.
what's issue here? have tried putting ajax call inside componentdidmount
, result same, if it's triggered ajax call explode(5-10 calls per second).
i hack , make count , stop @ 1, that's not right way solve it(i need find root cause :) )
sample code:
let sample = react.createclass({ getinitialstate : function () { return{ data: [], }; }, ajaxcall : function(somevalue) { // ajax call sets data $.ajax({ // ... }); }, rendertable(value, index) { // populates table // .. }, render : function () { let tabledata = this.state.data; if (tabledata) { this.ajaxcall(this.props.somevalue); // goes infinite loop return ( <popover id="popover-positioned-scrolling-left" title={this.props.somevalue}> <table striped bordered condensed hover> <thead> <tr> <th>header 1</th> <th>header 2</th> <th>header 3</th> </tr> </thead> <tbody> {tabledata.map(this.rendertable)} </tbody> </table> </popover> ) } else { return <div></div> } } });
because when setstate
, triggered re-rendering
of component. inside
ajaxcall : function(countryiso3) { // ajax call sets data $.ajax({ // ... }); },
you using setstate
set data in state variable, call render
again, , inside render
again making api
call, again setstate
......that's why infinite loop.
simple solution of problem api call inside componentdidmount
lifecycle method.
componentdidmount() invoked after component mounted. initialization requires dom nodes should go here. if need load data remote endpoint, place instantiate network request.
never mutate this.state directly, calling setstate() afterwards may replace mutation made. treat this.state if immutable.
update:
do api call inside onclick event.
lets say, want call api on click of text, write this:
<p onclick={this.ajaxcall}>click me fetch data</p> ajaxcall : function(countryiso3) { // ajax call sets data $.ajax({ // ... }); }
Comments
Post a Comment