Skip to content

Commit

Permalink
Allow connectToStore components to use props in getStores
Browse files Browse the repository at this point in the history
  • Loading branch information
drawveloper committed May 14, 2015
1 parent 3ac1f75 commit 7003703
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
9 changes: 4 additions & 5 deletions src/utils/connectToStores.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
*
* const MyComponent = React.createClass({
* statics: {
* getStores() {
* getStores(props) {
* return [myStore]
* },
* getPropsFromStores(props) {
Expand All @@ -27,7 +27,7 @@
* Example using ES6 Class:
*
* class MyComponent extends React.Component {
* static getStores() {
* static getStores(props) {
* return [myStore]
* }
* static getPropsFromStores(props) {
Expand Down Expand Up @@ -55,22 +55,21 @@ function connectToStores(Component) {
throw new Error('connectToStores() expects the wrapped component to have a static getPropsFromStores() method')
}

// Cache stores.
const stores = Component.getStores()

// Wrapper Component.
const StoreConnection = React.createClass({
getInitialState() {
return Component.getPropsFromStores(this.props)
},

componentDidMount() {
const stores = Component.getStores(this.props)
stores.forEach((store) => {
store.listen(this.onChange)
})
},

componentWillUnmount() {
const stores = Component.getStores(this.props)
stores.forEach((store) => {
store.unlisten(this.onChange)
})
Expand Down
21 changes: 21 additions & 0 deletions test/connect-to-stores-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,27 @@ export default {
assert.include(output, 'Foo: Bar')
},

'component can get use stores from props'() {
const LegacyComponent = React.createClass({
statics: {
getStores(props) {
return [props.store]
},
getPropsFromStores(props) {
return props.store.getState()
}
},
render() {
return React.createElement('div', null, `Foo${this.props.delim}${this.props.foo}`)
}
})

const WrappedComponent = connectToStores(LegacyComponent)
const element = React.createElement(WrappedComponent, {delim: ': ', store: testStore})
const output = React.renderToStaticMarkup(element)
assert.include(output, 'Foo: Bar')
},

'ES6 class component responds to store events'() {
class ClassComponent extends React.Component {
static getStores() {
Expand Down

0 comments on commit 7003703

Please sign in to comment.