Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflux how to listen for async action completed

From reading the docs I don't quite understand how Reflux async actions work. In particular I need to trigger something when an async action completes.

In one of my components I want to listen for an async action complete and then transition to a view.

mixins: [State, Navigation, Reflux.listenerMixin],

componentDidMount() {
  this.listenTo(actions.loadProject.completed, ()=>{this.transitionTo('info')});
},

I have created my action like this:

var actions = Reflux.createActions([
  "someSyncAction",
  "anotherSyncAction"
]);

actions.loadProject = Reflux.createAction({
  "loadProject": {children: ['completed','failed']},
});

And in my projectStore I have something like this:

 onLoadProject(id) {

    var url = '/api/projects/' + id;
    io.socket.get(url, (body, jwr) => {

      if(jwr.statusCode !== 200){
        console.error('Failed to load project', id, body);
        return actions.loadProject.failed();
      }

      var p = body;
      debug('loaded project', id, p);
      this.project = p;
      this.trigger(p);
      actions.loadProject.completed();
    });
  },

But it appears actions.loadProject.completed is not a function, so the above code won't work. What is the correct approach?

like image 864
Thijs Koerselman Avatar asked Feb 19 '15 14:02

Thijs Koerselman


1 Answers

I found that my original code didn't work because of one typo and one mistake. Below are the corrections.

mixins: [State, Navigation, Reflux.listenerMixin],

Should have been

mixins: [State, Navigation, Reflux.ListenerMixin],

I believe warnings for undefined mixins have been added to React, but apparently didn't make it into my version yet.

actions.loadProject = Reflux.createAction({
 "loadProject": {children: ['completed','failed']},
});

Should have been

actions.loadProject = Reflux.createAction({children: ['completed','failed']});

I had used the syntax from createActions instead. That's why loadProject.completed wasn't a function. Reflux created a plain action without complaining apparently.

In Tim Arney's example shows that you can keep the API call in a separate action listener and have the store only listen for the completed action. I think I prefer to keep the API call with the store logic. If anyone thinks there's a good reason not to I'd love to hear about it.

like image 111
Thijs Koerselman Avatar answered Sep 17 '22 23:09

Thijs Koerselman