Ad

Updating Page Content Using ReactJS And AJAX

- 1 answer

I'm new to react.js . I created a webpage with react.js which fetches data from json file (file is at server) and display it.

I want that changes in json file should reflect in webpage without reloading page so I used following code:

(this is not full code)

 getInitialState: function() {
    return {data: []};
  },
   componentDidMount: function() {
        this.loadFromServer();
        setInterval(this.loadFromServer, 2000);
      }

and loadFromServer():

loadFromServer: 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)
    });
  }

It works well.

But problem I'm facing is that it keeps on fetching json file data in every 2 secs even if there is no change in data.

Please see this: enter image description here

Here file size is only 8.28 KB, but in future it will increase. I want a solution that it should fetch data from JSON file at server only when there is a change in data. I'm implementing server using Nodejs (express).

Ad

Answer

Once the ajax call is finished, the client (browser) has no way to know what goes on server side without asking the server.

There are many ways to avoid the systematic fetching of a huge json payload :

  • ask for a json diff - cf https://www.npmjs.com/package/jiff for example but you will need to keep track of which version each client has
  • ask if there is new data available before fetching the json payload - you will need to give an ID to the json payload to compare the client side ID with the server side ID ; or you could timestamp the json and use the timestamp as ID so the server would know that the client has stale data
  • choose a realtime framework like socket.io so that the server will be able to inform the client that new data has arrived
  • use a solution based on HTTP 304
  • and probably many more
Ad
source: stackoverflow.com
Ad