javascript - Should I use setInterval when fetching data? -


i’m trying learn , use react in 1 project. have controller (in rails) outputs json:

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

and 1 component fetches data controller 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 present data best way allow admins menage data? example must allow admins delete users. know how send request server , delete 1 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 if there 2 admins working on same list or table , deleting users? before react using redirect_to /some/index.html , site refreshed , admin saw current state of database. i’m trying avoid refreshing whole site , first thought fetch data each half second:

...   tick() {     this.fetchdata()   };   componentdidmount() {     setinterval(()=> this.tick(), 500)   }; ... 

now admins make each 0.5 seconds request db , current data solution?

it depends on nature of data. if you're dealing dynamic data important users have up-to-date view of things, yeah, comments suggesting setting websocket connection push updates idea.

however, if you're dealing data doesn't change often, it's overkill. end scenarios user tries delete/edit user has been deleted? yes, infrequent , these situations can handled sending appropriate status codes , handling them in ui.


Comments