Skip to content

Instantly share code, notes, and snippets.

@jhollingworth
Last active August 29, 2015 14:10
Show Gist options
  • Save jhollingworth/707b9bf0e9a67397871c to your computer and use it in GitHub Desktop.
Save jhollingworth/707b9bf0e9a67397871c to your computer and use it in GitHub Desktop.
var UserState = Marty.createStateMixin({
listenTo: [ActionStore, UserStore],
getState: function () {
return {
user: UserStore.getById(123),
createUser: ActionStore.getStatus(this.createUserToken)
};
}
})
var User = React.createClass({
mixins: [UserState],
render: function () {
var user = this.state.user;
var createUser = this.state.createUser;
if (createUser)
if (createUser.inProgress) {
// some spinner
} else if (createUser.failed) {
return <Error error={createUser.error} />
}
}
if (user.loading) {
return <Loading />;
}
if (user.failed) {
return <ErrorPage error={user.error} />
}
return <div className="user">{user.result.name}</div>
},
saveUser: function () {
this.setState({
createUserToken: UserActionCreators.createUser({
name: "Foo"
})
});
}
});
var UserActionCreators = Marty.createActionCreators({
createUser: function (user) {
return this.dispatch("ADD_USER", user).then(function () {
return UserAPI.createUser(user);
});
},
receiveUser: function (user) {
return this.dispatch("ADD_USER", user);
}
})
var UserAPI = Marty.createHttpAPI({
createUser: function (user) {
return this.post('/users/', user).then(function (user) {
return UserActionCreators.receiveUser(user);
});
}
});
var UserStore = Marty.createStore({
handlers: {
addUser: "ADD_USER"
},
addUser: function (user) {
this.state[user.id] = user;
this.hasChanged();
},
getById: function (id) {
return this.query(id, function () {
return this.cache[id]
}, function () {
return UserAPI.getById(id)
})
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment