March 12, 2015

Since Flux isn’t a traditional MVC framework, it’s important to remember that you should still specify what ‘models’ your app depends on.

You can do this by defining objects in your stores. Assumming you’re using lodash:

//AuthStore.js

//...

//this tells what our user 'model' will look like
//and what we can expect from the server.
var userTemplate = {
  first_name: '',
  last_name:  '',
  birthday:   '',
  email:      '',
  username:   '',
  auth_token: ''
};

var currentUser = {};

var AuthStore = {
  getUserTemplate(){
    return userTemplate;
  },

  getCurrentUser(){
    return currentUser;
  },

  //credentials: object containing user credentials
  signIn(credentials){
    $.ajax({
      type: "POST",
      url: "/user/sign_in",
      data: credentials,
      success: function(data){
        currentUser = _.extend({}, userTemplate, data.user_info);
        //...
      }
    });
    //...
  },

  signOut(){
    $.ajax({
      type: "POST",
      url: "/user/sign_out",
      success: function(){
        currentUser = {};
        //...
      }
    });
    //...
  }
};

This is especially useful for the getInitialState() method of your React components.

//NavComponent.js

//...
import AuthStore from 'AuthStore';
//...

React.createClass({
  getInitialState(){
    //Provide empty non-null data so that the
    //component can render without raising an error
    return {
      currentUser: AuthStore.getUserTemplate()
    };
  },

  componentDidMount(){
    //Add a listener for AuthStore to authChange()
  },

  componentWillUnmount(){
    //Remove the listener for AuthStore to authChange()
  },

  authChange(){
    this.setState({
      currentUser: AuthStore.getCurrentUser()
    });
  },

  render(){
    return (
      <div>
        Hello, {this.state.currentUser.first_name}
      </div>
    );
  }
});
blog comments powered by Disqus