Do something once, then every 15 seconds in response to js

I have the following code:

var Panel = React.createClass({ getInitialState: function () { return { user_id: null, blogs: null, error: false, error_code: '', error_code: '' }; }, shouldComponentUpdate: function(nextProps, nextState) { if (nextState.error !== this.state.error || nextState.blogs !== this.state.blogs || nextState.error_code !== this.state.error_code ) { return true; } }, componentDidMount: function() { var self = this; var pollingInterval = setInterval(function() { $.get(self.props.source, function(result) { if (self.isMounted()) { self.setState({ error: false, error_code: '', error_message: '', blogs: result.user.blogs, user_id: result.user.id }); } }.bind(self)).fail(function(response) { self.setState({ error: true, error_code: response.status, error_message: response.statusText }); }.bind(self)); }, 1000); }, render: function() { ... } }); 

An important part to focus on is componentDidMount . It will be retrieved every second regardless of error or not. The rendering function, assuming theres an error, will display the corresponding method. So for all intense and targeted, this code does exactly what I want it to do, it extracts, if it fails, it is extracted again until it is successful.

But I need to make some changes, and this is where I got lost. I want to say: To receive once, pass or fail - it does not matter. THEN every 15 seconds after this initial fetch, try again - regardless of pass or failure

Normally, I would set aside the base collection and router along with the polling assistant to do all this, but in this particular case there is no need for additional overhead. So that's where I am at a standstill. How to achieve what I am trying to achieve ?

+6
source share
1 answer

You can simply reorganize your code a bit to be able to call your polling function in several different ways (for example, manually, and then at a given interval):

 componentDidMount: function() { this.startPolling(); }, componentWillUnmount: function() { if (this._timer) { clearInterval(this._timer); this._timer = null; } }, startPolling: function() { var self = this; setTimeout(function() { if (!self.isMounted()) { return; } // abandon self.poll(); // do it once and then start it up ... self._timer = setInterval(self.poll.bind(self), 15000); }, 1000); }, poll: function() { var self = this; $.get(self.props.source, function(result) { if (self.isMounted()) { self.setState({ error: false, error_code: '', error_message: '', blogs: result.user.blogs, user_id: result.user.id }); } }).fail(function(response) { self.setState({ error: true, error_code: response.status, error_message: response.statusText }); }); } 
+12
source

Source: https://habr.com/ru/post/983118/


All Articles