Search code examples
reactjsrefluxjs

How to get initial state with AJAX in a Store with Reflux


Recently I've been working on React and Reflux. The part I get stuck is that I can't get initial state with AJAX in a store in Reflux. What I tried is just calling the ajax($.getJSON) in getInitialState function in Store.js, setting the initial state with the AJAX response(JSON), and figuring out what the state is. I expected the output got from AJAX call would be JSON Array list, but the actual output will be undefined

So how can I getInitialState with AJAX in a Store with Reflux?

The code is something like this...

// in store.js
getInitialState: function() {
  $.getJSON('/sample').done(function(result){
    this.list = result;
  });
  return this.list;
}

// in sampleApp.jsx
mixins: [Reflux.connect(Store, "list")],

  render() {
    console.log(this.state.list);
    // I expected this output would be JSON lists, but the actual output will be undefined.

    return ();
  } 

Solution

  • There are a number of problems with this code:

    getInitialState: function() {
      $.getJSON('/sample').done(function(result){
        this.list = result;
      });
      return this.list;
    }
    

    First off, your returning this.list before the Ajax request comes back with the data. That effectively means that you are returning undefined from that function. The second problem is that you are using this inside the Ajax callback, which won't point to the Reflux store. You need to use an arrow function and an ES6 transpiler for that.

    But you shouldn't be doing an Ajax request in getInitialState anyway. What you're looking for is something like this:

    var MyStore = Reflux.createStore({
      getInitialState: function () {
        return {
          list: []
        }
      },
      init: function () {
        var self = this;
        $.getJSON('/sample').done(function (result) {
          self.trigger({list: result});
        });
      }
    });