Skip to content

Commit

Permalink
Merge e51b54b into d511892
Browse files Browse the repository at this point in the history
  • Loading branch information
lipp committed Feb 14, 2017
2 parents d511892 + e51b54b commit 753d39b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
14 changes: 12 additions & 2 deletions src/index.js
Expand Up @@ -7,8 +7,15 @@ const fetchActions = {
unfetch
}

const withJet = (mapStateToConnection, fetchers = {}) => {
return Component => connect(mapStateToConnection, fetchActions)(class extends React.Component {
const withJet = (mapStateToConnection, fetchers = {}, shouldRender) => {
const mapStateToProps = state => {
const {connection} = mapStateToConnection(state)
return {
connection,
shouldRender: shouldRender ? shouldRender(state) : true
}
}
return Component => connect(mapStateToProps, fetchActions)(class extends React.Component {
fetchAll (connection) {
Object.keys(fetchers).forEach(fetchId => {
this.props.fetch(connection, fetchers[fetchId], fetchId)
Expand Down Expand Up @@ -37,6 +44,9 @@ const withJet = (mapStateToConnection, fetchers = {}) => {
}

render () {
if (!this.props.shouldRender) {
return null
}
return <Component {...this.props} />
}
})
Expand Down
30 changes: 26 additions & 4 deletions test/index.js
Expand Up @@ -70,13 +70,35 @@ describe('withJet', () => {
const connection = {url: 'ws://localhost:1999', user: 'john', password: '12345'}
const ComponentWithJet = withJet(state => ({connection}), fetchers)(Container)
const wrapper = mount(<ComponentWithJet store={store} />)
let once
store.subscribe(() => {
if (store.getState().foo && !once) {
const unsubscribe = store.subscribe(() => {
if (store.getState().foo) {
assert.equal(store.getState().foo, 123)
assert.equal(wrapper.find('h1').text(), '123')
unsubscribe()
wrapper.unmount()
done()
}
})
})

it('should respect shouldRender if defined', done => {
const store = configureStore(combineReducers({foo: single('foo')}))
const fetchers = {
foo: {path: {startsWith: 'foo'}}
}
const connection = {url: 'ws://localhost:1999', user: 'john', password: '12345'}
const shouldRender = state => state.foo
const ComponentWithJet = withJet(state => ({connection}), fetchers, shouldRender)(Container)
const wrapper = mount(<ComponentWithJet store={store} />)
const unsubscribe = store.subscribe(() => {
if (!store.getState().foo) {
assert.equal(wrapper.find('h1').length, 0)
}
if (store.getState().foo) {
assert.equal(store.getState().foo, 123)
assert.equal(wrapper.find('h1').text(), '123')
unsubscribe()
wrapper.unmount()
once = true
done()
}
})
Expand Down

0 comments on commit 753d39b

Please sign in to comment.