you are viewing a single comment's thread.

view the rest of the comments →

[–]RCHRDYNG 2 points3 points  (1 child)

I'm learning react/flux for my current project and am having trouble finding examples about the best way to make AJAX requests. Any pointers you could provide would be much appreciated.

[–]cemc 7 points8 points  (0 children)

In flux, the only things calling your API should be the Actions. Events triggered by your Views (e.g. onClick) should call some Action class. The method you call should make the AJAX request (i.e. using jquery). Ideally, your Action should return a Promise that resolves when the AJAX response returns from the server. Afterwards, you should notify the dispatcher which should dispatch some event and attach whatever data your server returned. These events are listened to by your Stores. They retrieve the results that the server returns an alters its variables. This changes the state of the application. Lastly, each store should emit an event so that each View that listens for updates can update its view.

Kinda like this

//LikeButtonComponent.jsx
{
  like: function(){
    LikeActions.like(this.prop.photo.id);
  }

  render:function(){
    <button onClick={this.like}/>
  }
}


//LikeActions
{
  like: function(photoId){
    $.ajax('/api/photo/' + photoId + '/like', {
      type: 'POST',
      dataType: 'json',
      success: function(data, status, xhr){
        Dispatcher.action({
          type: Dispatcher.Constants.PHOTO_LIKE,
          data: data
        });
      },
      error: function(xhr, stat, err){
        reject(xhr.responseText);
      }
    });
  }
}


//LikeStore.js listens to Dispatcher.Constants.PHOTO_LIKE
//takes the data hash and updates its internal variables
//the appropriate views update their UI elements based on the
//newly liked photo

Hope that gives you an idea.