简体   繁体   中英

How do I continually update my ReactJS client from my Ruby REST/CRUD API without polling?

BACKGROUND

I'm building a simple ReactJS application as a proof of concept; with Flux architecture and all.

I have a Ruby and MongoDB data layer API built using Sinatra and Mongoid .

A front-end served statically using ReactJS , JSX , and Fluxxor .

I currently fetch the application state using a click handler which runs the following function:

function(callback){
  var the_url = (this.state.isSelected) ? '/disable' : '/enable' ;
  $.ajax({
    url: the_url,
    dataType: 'json',
    cache: false,
    success: function(data) {
      callback(data);
    }.bind(this),
    error: function(xhr, status, err) {
      console.error(the_url, status, err.toString());
    }.bind(this)
  });
}

It is a simple AJAX call. I understand I could achieve some sort of real-time by refactoring a little and having a piece of code similar to the one above running periodically; basically polling .

I've read and have been told that the "true react way" of doing things would be to have the back-end notifying the front-end when the state of the app changes and that the way to achieve this reliably would be using WebSockets .

BOTTOM-LINE

Taking into account the stack I have described, what libraries should I use for handling these sockets on either end of the application, and what would the simplest possible implementation look like?

Your solution is not dependent on you using React, you should use the same way of doing real-time updates as you would if you had used any front-end technique. The problem with WebSockets are mainly that the browser support have been a bit erratic, socket.io is a quite popular way to get around that.

Socket.io is mostly geared towards Node.js, but should be workable from any backend. Here is a write-up on using it with Rails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM