Search code examples
javascriptnode.jsreactjsflux

Cannot trigger alt store with alt action (Flux)


I'm developing a flux frontend program with goatslacker/alt. And I have problem triggering store to update with action. The listener is not functioning as I expected it to be.

The code I'm working on is quite complicated now. I'll try to simplify my problem into the following code. I expect it to log "Hello World! msg: Some message" in the end. Apparently, the listener hello() doesn't even run.

This is the main javascript (ES6) file to be run:

import alt from './alt';

class DummyActionsProto {

  sayHello(msg) {
    console.log("sayHello", msg);
    return {msg}
  }

}
var DummyActions = alt.createActions(DummyActionsProto);

class DummyStoreProto {

  constructor() {
    this.bindListeners({
      hello: DummyActions.sayHello,
    });

    this.state = {
      items: [],
    };
  }

  hello(msg) {
    console.log("Hello World! msg: "+msg);
  }

}
var DummyStore = alt.createStore(DummyStoreProto, 'DummyStore');

// trigger the action
DummyActions.sayHello("Some message");

The ordinary alt.js code it includes:

import Alt from 'alt';
module.exports = new Alt();

What is my problem?


Solution

  • In short the store can only catch the action if you add this.dispatch() in the action method. So instead of return anything in that method, you should run this.dispatch() (with or without parameter). The listener will be run with the parameters of this.dispatch().

    The corrected version:

    import alt from './alt';
    
    class DummyActionsProto {
    
      sayHello(msg) {
        console.log("sayHello", msg);
        this.dispatch(msg); // **instead of return, you should do this**
      }
    
    }
    var DummyActions = alt.createActions(DummyActionsProto);
    
    class DummyStoreProto {
    
      constructor() {
        this.bindListeners({
          hello: DummyActions.sayHello,
        });
    
        this.state = {
          items: [],
        };
      }
    
      hello(msg) {
        console.log("Hello World! msg: "+msg);
      }
    
    }
    var DummyStore = alt.createStore(DummyStoreProto, 'DummyStore');
    
    // trigger the action
    DummyActions.sayHello("Some message");