Last active
August 29, 2015 14:19
-
-
Save sgwilym/52640d38f17313e5bada to your computer and use it in GitHub Desktop.
Embedded flux entity class in Store with custom getters for associations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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