React Js, Reflux render before ajax answer

I would like to get a list of my users with api call and display a table with data.

At the moment, I can get the data, but if I try to display it, I have an error.

I think the reaction is rendering before the api call no longer understands why.

Here is my code:

var Actions = Reflux.createActions([
  "fetchList"
]);

Here is my store:

var bannersStore  = Reflux.createStore({
  users: { data : {}},
  listenables: [Actions],

  init: function() {

    this.fetchList();

  },
  fetchList: function(){

    var self = this;

    reqwest({
      url: 'http://localhost:9080/api/member.json',
      method: 'get',
      success: function (resp) {
        console.log('fetch complete');
        self.users = resp;
        self.trigger({users :resp});

      }
    });
  }

});

Here is my React class:

var Users = React.createClass({

    getInitialState: function() {
        return {users : UsersStore.fetchList()};
    },

    render: function() {

        var usersRows = this.state.users.data.map(function(user, i) {

              return (
                  <tr key={i}>
                      <td><Link to="user" params={{ id: user.id }}>{user.attributes.firstname + ' ' + user.attributes.lastname}</Link></td>
                      <td>{user.attributes.email}</td>
                      <td>{user.status}</td>
                      <td>{user.language}</td>
                  </tr>
              )
          });

          return (
              <div>
                  <table className="table table-striped">
                      <thead>
                      <tr>
                          <th>Name</th>
                          <th>Image</th>
                          <th>URL</th>
                          <th>Active?</th>
                      </tr>
                      </thead>
                      <tbody>
                      { usersRows }
                      </tbody>
                  </table>
              </div>
          )

        }

});

this.state.users.data is undefind and I have an error (undefined).

Thank you for your help.

+4
source share
2 answers

I would suggest this model. An example of a reflux pattern can be found at https://github.com/calitek/ReactPatterns React.14 / ReFluxSuperAgent.

    getInitialState: function() {
        return {users : {data: []}};
    },
    componentDidMount() {
      this.unsubscribe = UsersStore.listen(this.storeDidChange);
      Actions.fetchList();
    },
    componentWillUnmount() { this.unsubscribe(); },
    storeDidChange(newData) {
      this.setState(newData);
    },
Run codeHide result
+2

, , ​​ ?

, , . success, , React.

Reflux, , :

  • , , , , ,

  • success .

- Reflux REST, .

+1

Source: https://habr.com/ru/post/1616769/


All Articles