Skip to content

Instantly share code, notes, and snippets.

@sgwilym
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgwilym/52640d38f17313e5bada to your computer and use it in GitHub Desktop.
Save sgwilym/52640d38f17313e5bada to your computer and use it in GitHub Desktop.
Embedded flux entity class in Store with custom getters for associations
import { Store } from 'flummox';
import React from 'react/addons';
export default class UserStore extends Store {
constructor(flux) {
super();
this.registerAll(this.addUsers);
this.state = {
users: {}
};
this.userClass = class User {
constructor(props) {
Object.assign(this, props);
this._postIds = props.posts;
}
get posts() {
// PostStore would have a similar embedded Post class and getPosts as this Store.
return flux.getStore('posts').getPosts(this._postIds);
}
};
}
addUsers(response) {
if (checkIfHasEntities(response, 'users') === false) return;
var userEntities = {};
for (let user in response.entities.users) {
userEntities[user] = new this.userClass(response.entities.users[user]);
}
let nextState = React.addons.update(this.state, {
users: {$merge: userEntities}
});
this.setState(nextState);
}
getUsers(ids) {
return ids.map(id => this.state.users[id]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment