Skip to content

Instantly share code, notes, and snippets.

@elado
Created October 18, 2016 19:50
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 elado/c977a00a34f89229e7b33673348d3a21 to your computer and use it in GitHub Desktop.
Save elado/c977a00a34f89229e7b33673348d3a21 to your computer and use it in GitHub Desktop.
mobxStoresToProps
import React, { Component } from 'react'
import { omit } from 'lodash-bound'
import { observer, inject } from 'mobx-react'
// usage:
//
// @mobxStoresToProps(['entityStore', 'userStore'], (entityStore, userStore, { conversationId }) => {
// const conversation = entityStore.conversation.getById(conversationId)
// const user = conversation.counterParty
// return {
// conversation,
// user,
// loadData(userId, organizationId) {
// userStore.find(userId)
// userStore.findProfileForOrganization(userId, organizationId)
// }
// }
// })
const mobxStoresToProps = (storeNames, factory) => WrappedComponent => {
WrappedComponent = observer(WrappedComponent)
@inject(...storeNames)
@observer
class MobxStoresToPropsWrapper extends Component {
static displayName = `MobxStoresToPropsWrapper(${WrappedComponent.displayName || WrappedComponent.name})`
render() {
const propsWithoutStores = this.props::omit(storeNames)
return <WrappedComponent {...propsWithoutStores} {...this._calcSelectors()} />
}
_calcSelectors() {
const stores = storeNames.map(key => this.props[key])
const state = factory(...stores, this.props)
return state
}
}
return MobxStoresToPropsWrapper
}
export default mobxStoresToProps
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment