Mislavoo7
Mislavoo7

Reputation: 697

Should I use setInterval when fetching data?

I’m trying to learn and then use react in one project. I have a controller (in rails) that outputs json:

...
  def index
    @users = User.order(created_at: :desc)
    respond_to do |format|
      format.json { render json: @users}
    end
  end
...

And one component that fetches data from this controller like this:

...
  fetchData() {
    fetch('admin/users.json', {credentials: 'same-origin'})
      .then(function(response) {
        return response.json()
      }).then(function(json) {
        this.setState({data: json})
      }.bind(this))
      .catch(function(ex) {
        console.log('parsing failed', ex)
      });
  };
...

It’s not hard to present this data but what is the best way to allow admins to menage this data? For example I must allow admins to delete users. I know how to send the request to the server and delete one user:

...
  fetchData() {
    fetch('admin/users.json', {credentials: 'same-origin'})
      .then(function(response) {
        return response.json()
      }).then(function(json) {
        this.setState({data: json})
      }.bind(this))
      .catch(function(ex) {
        console.log('parsing failed', ex)
      });
  };

...

But what if there are two admins working on the same list or table and deleting users? Before react I was using redirect_to /some/index.html , the site was refreshed and the admin saw the current state of the database. I’m now trying to avoid refreshing the whole site and my first thought was to fetch data each half second:

...
  tick() {
    this.fetchData()
  };

 componentDidMount() {
    setInterval(()=> this.tick(), 500)
  };
...

Now the admins make each 0.5 seconds a request to the db and get the current data but is this really a good solution?

Upvotes: 1

Views: 2717

Answers (1)

TLadd
TLadd

Reputation: 6884

It depends on the nature of the data. If you're dealing with fairly dynamic data where it is important for your users to have an up-to-date view of things, then yeah, the comments suggesting setting up a websocket connection to push all updates is a good idea.

However, if you're dealing with data that doesn't change that often, then it's probably overkill. Will you end up with scenarios where a user tries to delete/edit a user that has already been deleted? Yes, but it will likely be very infrequent and these situations can be handled by sending back appropriate status codes and handling them in your ui.

Upvotes: 1

Related Questions