flux icon indicating copy to clipboard operation
flux copied to clipboard

Action Creator Callbacks?

Open wayneashleyberry opened this issue 11 years ago • 16 comments

Just hit a bit of a wall and hoping someone here could help...

I'm trying to implement adding a resource using Flux and can't figure out how it would fit in.

Here's the flow

  1. User clicks an "Add Article" button
  2. The click handler calls ArticleActionCreators.createArticle
  3. ArticleActionCreators.createArticle makes a POST request to the API and passes the response on to the ArticleStore
  4. Router navigates to /articles/1 where 1 is the id of the newly created Article.

The problem is, where do I hook in to the system to get the id of the newly created Article?

My first thoughts are to have a callback on the action creator, but that doesn't feel right...

Any ideas? Does this make any sense?

wayneashleyberry avatar Jan 08 '15 15:01 wayneashleyberry

Shouldn't createArticle issue the route change only when it has the server response from the POST (with the Id)? Otherwise how are you detecting a server error?

Sent from my iPhone

On Jan 8, 2015, at 7:45 AM, Wayne Ashley Berry [email protected] wrote:

Just hit a bit of a wall and hoping someone here could help...

I'm trying to implement adding a resource using Flux and can't figure out how it would fit in.

Here's the flow

User clicks an "Add Article" button The click handler calls ArticleActionCreators.createArticle ArticleActionCreators.createArticle makes a POST request to the API and passes the response on to the ArticleStore Router navigates to /articles/1 where 1 is the id of the newly created Article. The problem is, where do I hook in to the system to get the id of the newly created Article?

My first thoughts are to have a callback on the action creator, but that doesn't feel right...

Any ideas? Does this make any sense?

— Reply to this email directly or view it on GitHub.

sterpe avatar Jan 08 '15 16:01 sterpe

I.e. Because the dispatcher is guaranteed to be synchronous you can dispatch the payload , the store will be updated in the same priority and when dispatch function returns at the next line you can perform the route change. This should avoid nesting dispatches.

Sent from my iPhone

On Jan 8, 2015, at 7:45 AM, Wayne Ashley Berry [email protected] wrote:

Just hit a bit of a wall and hoping someone here could help...

I'm trying to implement adding a resource using Flux and can't figure out how it would fit in.

Here's the flow

User clicks an "Add Article" button The click handler calls ArticleActionCreators.createArticle ArticleActionCreators.createArticle makes a POST request to the API and passes the response on to the ArticleStore Router navigates to /articles/1 where 1 is the id of the newly created Article. The problem is, where do I hook in to the system to get the id of the newly created Article?

My first thoughts are to have a callback on the action creator, but that doesn't feel right...

Any ideas? Does this make any sense?

— Reply to this email directly or view it on GitHub.

sterpe avatar Jan 08 '15 16:01 sterpe

Hey @sterpe, that's what I'm thinking. Have the action creators support callbacks or return promises or something like that.

Would getting the article id from the action creator callback not conflict with Flux's philosophy of all data coming from stores?

Here's some pseudo code to demonstrate what I'm thinking...

var ArticleActionCreators = {

  createArticle: function() {
    var request = $.ajax({
      type: 'POST',
      url: '/article'
    });
    request.done(function(response) {
      Dispatcher.handleViewAction({
        actionType: 'NEW_ARTICLE',
        responseBody: response
      });
    });
    return request;
  }

};

var CreateArticleButton = React.createClass({

  createArticle: function(e) {
    e.preventDefault();
    var action = ArticleActionCreators.createArticle();
    // the following 4 lines are what i'm most concerned about
    action.done(function() {
      var id = ArticleStore.getNewlyCreatedArticleId();
      Router.navigate('/articles/'+id);
    });
  },

  render: function() {
    return <a href="#" onClick={this.clickHandler}>Create Article</a>;
  }

});

wayneashleyberry avatar Jan 09 '15 07:01 wayneashleyberry

Here's another option for the createArticle method:

createArticle: function(e) {
  e.preventDefault();
  var action = ArticleActionCreators.createArticle();
  // get the id directly from the action creator, might conflict with Flux's
  // philosophy of all data coming from stores?
  action.done(function(id) {
    Router.navigate('/articles/'+id);
  });
},

wayneashleyberry avatar Jan 09 '15 07:01 wayneashleyberry

As far as I understand Flux philosophy, you should have:

  • your action creator to dispatch 'article creation started' before sending ajax request; 'article created' and 'article create error' actions on ajax promise resolve/reject
  • your store moving to some 'creating article' state on 'article creation started' action so that the view could render some progress indicator
  • your store moving from 'creating article' state on 'article created' and either updating the route or notifying the view that the route should be updated
  • your store moving from 'creating article' state on 'article create error' and storing the error so the view could display it (and not updating the router)

Please correct me if I am wrong. I am interested in this workflow, too, so I would be glad to hear a solution from Flux developers.

sompylasar avatar Jan 09 '15 11:01 sompylasar

@sompylasar you are 100% correct. I'm intentionally leaving out a lot of those states and events because i'm just prototyping an application for now.

This is what i'm most interested in:

your store moving from 'creating article' state on 'article created' and either updating the route or notifying the view that the route should be updated

I've decided to go with returning the newly created article id from the action creator for now. It just seems like the simplest solution. I have a feeling this might change as time goes on though.

Here's my code:

var ArticleActionCreators = {

  createArticle: function() {
    var Deferred = new $.Deferred();
    API.POST('/articles').done(function(response) {
      dispatch({
        actionType: 'CREATE_ARTICLE',
        responseBody: response
      });
      Deferred.resolve(response.data.id);
    });
    return Deferred.promise();
  }

}

var CreateArticleButton = React.createClass({

  mixins: [Router.Navigation],

  getInitialState: function() {
    return {
      adding: false
    };
  },

  clickHandler: function(e) {
    e.preventDefault();
    e.target.blur();
    this.createAndTransition();
  },

  createAndTransition: function() {
    this.setState({adding: true});
    ArticleActionCreators.createArticle().done(function(id) {
      this.setState({adding: false});
      this.transitionTo('article', {id: id});
    }.bind(this));
  },

  render: function() {
    if (this.state.adding) {
      return <span className="text-muted">Adding Article…</span>;
    }

    return <a href="#" onClick={this.clickHandler}>Add Article</a>;
  }

});

wayneashleyberry avatar Jan 09 '15 12:01 wayneashleyberry

@sompylasar I would think maybe have a generalized request state store that managed that and could keep track of multiple concurrent request. It seem like keeping track of all that in the article store could lead to it being overly messy or in an inaccessible state for some other dispatch, plus you need to handle it for other types of requests too.

sterpe avatar Jan 09 '15 12:01 sterpe

@wayneashleyberry What I see from your code is that you track 'article creating' state in your view but you should in the article store. When you move this state to the store, you won't need the promise returned from the action creator.

Mixing a router into a button view is wrong, they have nothing in common. There should be some store that tracks the whole app state including the current route which is global (that's how browsers work having a single URL for an app state, we cannot change it).

@sterpe Yes, you could additionally have a store that tracks all requests in a single place. But you should track articles state in article store for those views which only work with articles.

sompylasar avatar Jan 09 '15 16:01 sompylasar

P.S. If you are "leaving out intentionally", then you should also leave out Flux philosophy instead of twisting and bending it to make less architecture components than the philosophy requires to implement it.

sompylasar avatar Jan 09 '15 17:01 sompylasar

Having calbacks do more than just dispatching actions breaks the Flux flow. This is what happens in your code, you attach a callback that changes the view state and the router state, but this change does not happen as a result of handling the store's change event.

sompylasar avatar Jan 09 '15 17:01 sompylasar

@sterpe and @sompylasar thanks for jumping in here. you guys are correct -- all application state should be maintained in the stores, not the view components.

fisherwebdev avatar Jan 09 '15 17:01 fisherwebdev

@sompylasar the reason i'm asking is because i'm trying to stick to the Flux philosophy but there's no documentation on using routers or anything like that.

So if I have CREAT_ARTICLE and CREATE_ARTICLE_SUCCESS actions, some component still needs to listen to them and trigger a transition on the router... which component should do this? The top-level App component?

wayneashleyberry avatar Jan 09 '15 22:01 wayneashleyberry

@wayneashleyberry I think this should be like follows.

There should be a store that tracks the current route because it's a part of the application state (let's name it AppStore if it is responsible for more than that, or just RouteStore).

Both the ArticleStore and the AppStore/RouteStore handle ARTICLE_CREATE_SUCCESS action.

The ArticleStore updates its internal data and emits a change event that is handled by the views (the button becomes enabled again, the new article appears in the list etc.).

The AppStore/RouteStore depends on the ArticleStore via waitFor, updates the route if required (you could put a flag into the action payload whether the navigation is required or not) and emits a change event so the view displays the page that corresponds to the current route.

sompylasar avatar Jan 09 '15 23:01 sompylasar

@sompylasar that helped a lot, thanks so much :)

wayneashleyberry avatar Jan 22 '15 07:01 wayneashleyberry

What about an action which depends on the result of another action?

I have a form component to CREATE/UPDATE 2 entities :

  1. Submit form
  2. First call APIAction.saveEntityData and save "parentEntityData"
  3. Second call APIAction.saveEntityData and save "childEntityData" with the "parentEntityData" id received from server.

Does it make sense to add a callback to action payload ?

APIAction.saveEntityData({
    entity: 'parentEntity',
    model: parentModel,
    next: (parentEntityId) => {
        APIAction.saveEntityData({
            entity: 'childEntity',
            model: childModel.set('parentId', parentEntityId)
        })          
    }
})

loun4 avatar Sep 17 '15 15:09 loun4

@loun4 it sounds like you need to split that up into two actions.

APIAction.saveEntityData({...});

// Which causes an api request somewhere, where you do:
// (assuming a promise-like interface)
request.then((parentEntityId) => {
  // In this action you can do anything that requires the request
  // to have been completed.
  APIAction.entityDataSaved({...});
});

kyldvs avatar Sep 17 '15 16:09 kyldvs