javascript - Warning: Can only update a mounted or mounting component while calling api inside setInterval (React Native) -


i have been working on app need make api call every 30s , set response in state. doing inside setinterval. have component rendered on screens in app. (same component setinterval is). seems work when press button go previous screen, warning 'setstate on unmounted component'. remember, component mounted again in screen also. enough words, let me have code here.

songactivitybar.js

componentdidmount(){   _ismounted = true   this._timer = true;   this.startpolling(); }     componentwillunmount() {     _ismounted = false;     this._timer && clearinterval(this._timer);     this._timer = false;   }    startpolling=() => {       if (_ismounted){           this.fetchnowplaying(); // once , start ...           this._timer = setinterval(() => this.fetchnowplaying(), 30000);       }   }    fetchnowplaying() {     fetch(url, {     ..........      .then( (response) => {       this._timer && this.setstate({loading: false, nowplaying: response.message});     ........     });   } 

as clicking on screen of app, component songactivitybar.js loaded, coming screen nav.pop() or android button gives me warning.

p.s: using navigator navigating between screens (can't change library right now)

react native version - 0.45.1 

you need keep timer in state in order keep alive during lifecycle of component :

componentdidmount(){    this.fetchnowplaying();    const timer = setinterval(this.fetchnowplaying, 30000);    this.setstate({ timer });  }    componentwillunmount() {    clearinterval(this.state.timer);  }

reference here.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -