Search code examples
javascriptreactjsreactjs-fluxfluxreact-alt

React Action Callback do transition best practice


Case is that I add a new Item by click to my user over an action. When the Items is added the ActiveItemStore will be updated and I want then navigate to the active Item. But currently the transition is called before the Store is updated.

Current Code:

var actionListener = new ActionListeners(alt);
var listenerRef = actionListener.addActionListener(MyItemActions.ADDED,
    function() {
        setTimeout(function() { // Fixes Cannot dispatch in the middle of a dispatch.
             this.transitionTo('active-item', {locale: user.locale});
             // will be called before the ActiveItemStore is updated
        });
    }.bind(this));
    actionListener.removeActionListener(listenerRef);
}.bind(this));

// call action
MyItemActions.add({
    id: item.id,
    active: true
});

Do I need to use waitFor for this case or whats the best practice, and how to avoid the dispatch in dispatch without setTimeout?


Solution

  • In a nutshell: the Action function should not have a callback to do the transition. The typical flow would be:

    1. Your views listens to changes in the store
    2. In your view, the user clicks something
    3. The view calls an action (without timeout)
    4. The store then responds to the action, probably an update to active-item.
    5. The view notices the update to the store, and then transitions to the new state.

    A good tutorial on using the alt library for flux can be found here: http://alt.js.org/guide/