StinkyTotoro StinkyTotoro - 5 months ago 33
Node.js Question

Using react to get data from server and update component's state

I want to get a random number from the server every 5 seconds and I have done this using jquery/ajax

I am a bit confused as to the steps I would need to take using react to do this, this is my original script:

<script type="text/javascript">
fetchData();
$(document).ready(function() {
setInterval(fetchData, 5000);
});
function fetchData(){
$.ajax({
url: "/realtime/show",
type: "GET",
contentType: 'application/json',
success: function(result) {
$("#result").html(result.data);
}
});

}



Answer

In the component's componentDidMount call you can setup your interval, passing it a function which will make your AJAX call. Then within the callback of the AJAX call you can set the components state in some fashion (be careful with this). Then your render method you simply use the state as you need to. Make sure to clear your interval when the component unmounts so it doesn't keep running. The following is a simple example:

var AjaxCall = React.createClass({
    intervalId: null,
    request: null,
    getInitialState: function() {
        return {
            data: null
        };
    },

    componentDidMount: function() {
        this.intervalId = setInterval(this.fetchData, 5000);
    },

    componentWillUnmount: function() {
       if (this.intervalId) {
           clearInterval(this.intervalId)
           this.intervalId = null;
       }

       if (this.request) {
           this.request.abort();
           this.request = null;
       }
    },

    fetchData: function() {
        this.request = $.ajax({
            url: "/realtime/show",
            type: "GET",
            contentType: 'application/json',
            success: function(result) {
                var d = // process results
                this.setState({ data: d });
            }.bind(this)
        });
    },

    render: function() {
        // use this.state.data here however you need ot
        if (!this.state.data) {
            return <div>No data</div>
        }

        return <div>{this.state.data}</div>;
    }
});

ReactDOM.render(
  <AjaxCall />,
  document.getElementById('container')
);

You can see more information about making AJAX calls from components (such as for initial data loading) here