Search code examples
javascriptreactjsecmascript-6flux

How to wait for a dispatch happening in one store from another store


I am using Flux from Facebook, react, ES6.

I'm having different problems with those singleton stores. However the recurring one is the following. I dispatch one action from one component and I have two stores (StoreA, StoreB) listening for that action.

My two stores are in two different files and in each, I export the singleton store instance. Both stores are already imported in their relevant container (a React component view). I want StoreA to wait for StoreB to finish processing the current dispatch, before starting the process in StoreA.

I have read the doc and there is the waitFor method that can be used with the token returned by the register method from the dispatcher. However my two stores are in different files. Cannot find a way to access StoreB's dispatch token from StoreA...

In other words:

ReactComp.js

...
handleClick() {
    dispatcher.dispatch({
        type: 'ACTION1'
    });
}

StoreA.js

class StoreA {
    constructor() {
        this.dispatchToken = dispatcher.register((action) => {
            switch(action.type) {
                case 'ACTION1':
                    // do something...
                    break;
            }
        });
    }
}

export default new StoreA();

StoreB.js

class StoreB {
    constructor() {
        dispatcher.register((action) => {
            switch(action.type) {
                case 'ACTION1':
                    dispatcher.waitFor([storeADispatchToken]); //how to get the dispatchToken from Store A... 
                    break;
            }
        });
    }
}

export default new StoreB();

I am new to the react and flux architecture, the answer could be obvious and sorry if it is, however with all the hours put into looking unsuccessfully for an answer, I am betting on SO..


Solution

  • Import StoreA into StoreB and you should be able to reference the token:

    import StoreA from 'path/to/StoreA.js';
    // or if you're not using es6 imports:
    // const StoreA = require('path/to/StoreA.js');
    
    class StoreB {
      constructor() {
        dispatcher.register((action) => {
          switch(action.type) {
            case 'ACTION1':
              dispatcher.waitFor([StoreA.dispatchToken]);
              break;
            }
        });
      }
    }
    
    export default new StoreB();