2

I am new to React, I have gone through the official React tutorials on how to use React as a standalone service and have just gone through this tutorial on using the react-rails gem in a Rails App, which for the most part I have appropriated to be exactly what I need. The problem I'm encountering is that I need to implement some sort of simple API polling for my little React page, but I can't seem to find documentation anywhere on how to best implement this in react-rails.

During the react tutorial it tells us to use pollinterval = 2000 when declaring the data source to poll the source every 2000 milliseconds. I tried implementing this as follows, but to no avail:

@Records = React.createClass
    getInitialState: ->
      $.ajax
        method: 'GET'
        url: '/records'
        dataType: 'JSON'
        success: (response) ->
          records: response
      pollinginterval: 2000
    ...

Unfortunately when I load the page not only does no content actually display, but it appears to not be querying the database at all - even initially. This leads me to believe that this is not the proper location for the AJAX call / setting the pollinginterval, but nothing in my googling has been particularly helpful.

Zubatman
  • 1,235
  • 3
  • 17
  • 34

2 Answers2

2

How about this approach?

@Records = React.createClass
  getInitialState: ->
    # `this.state.records` is empty now, but will be loaded by AJAX
    {
      records: [] 
    }

  componentDidMount: ->
    # Ping every 2s
    @_recordsInterval = setInterval =>
        @_loadRecords()
      , 2000
    # Load initial data: 
    @_loadRecords()

  componentWillUnmount: -> 
    # clean up loose ends: 
    clearInterval(@_recordsInterval)
    @_recordsRequest?.abort()

  # ...

  _loadRecords: ->
   # Fetch records from the server and store it as `this.state.records`
   @_recordsRequest = $.get "/records", (data) => 
     @setState(records: data)
rmosolgo
  • 1,854
  • 1
  • 18
  • 23
  • It polls, but only once. How would you recommend I get it to poll constantly? – Zubatman Mar 17 '16 at 16:10
  • Oops! I had `setTimeout` instead of `setInterval` (and likewise for `clearTimeout`/`clearInterval`). I updated my answer to use `setInterval` which will continue to poll the server. – rmosolgo Mar 17 '16 at 17:39
0

I would recommend that you do preform your ajax call in componentDidMount instead of getInitialState.

Check out this tutorial for loading ajax data. https://facebook.github.io/react/tips/initial-ajax.html

Terenced
  • 665
  • 2
  • 6
  • 17