I asked the question of regularly receiving data from the server. On Habré, I found how to implement polling: a couple of methods are added to the component:

loadNewDataFromServer: function() { $.ajax({ url: this.props.url, dataType: 'json', cache: false, success: function(data) { this.setState({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, componentDidMount: function() { this.loadNewDataFromServer(); setInterval(this.loadNewDataFromServer, this.props.pollInterval); } 

Question 1: I understand correctly, before removing a component from the DOM (when switching the user's attention to another component that is completely independent of the data received), to save traffic, you need to stop the requests as follows:

 componentWillUnmount(){ // подскажите, что здесь? } 

Question 2: m., Will you advise any other methods of updating data on the client?

Thank you in advance.

  • one
    save the timer identifier this.timer = setInterval(... , in componentWillUnmount () stop this timer clearInterval( this.timer) . - Sergiks
  • one
    Ideologically, there are two main approaches. Approach 1: keep this logic in storage (if you work with a reactor, then you will most likely need some kind of flux storage). Campaign 2: to keep this logic in top-level views, which are essentially rather “view controllers”. - Duck Learns to Take Cover
  • one
    Other methods: long-field, web sockets. For most tasks, sockets are better now. - Duck Learns to Take Cover
  • In componentWillUnmount, you must make clearInterval, otherwise you will call setState for a non-existent component (warning will pop up in dev mode). - alexes

1 answer 1

You can use react-timer-mixin for this, it will drop setInterval itself when the component is deleted.

 import React from 'react'; import TimerMixin from 'react-timer-mixin'; const Example = React.createClass({ mixins: [TimerMixin], loadNewDataFromServer() { // ... }, componentDidMount() { this.setInterval(this.loadNewDataFromServer, this.props.pollInterval); }, });