chore(addSubscriptions): move into own module

This commit is contained in:
Julien Fontanet 2018-01-05 15:42:37 +01:00
parent e446eb0cd0
commit 242d9e20c4
2 changed files with 32 additions and 42 deletions

View File

@ -0,0 +1,28 @@
import map from 'lodash/map'
import React from 'react'
const call = fn => fn()
// `subscriptions` can be a function if we want to ensure that the subscription
// callbacks have been correctly initialized when there are circular dependencies
export const addSubscriptions = subscriptions => Component =>
class SubscriptionWrapper extends React.PureComponent {
_unsubscribes = null
componentWillMount () {
this._unsubscribes = map(
typeof subscriptions === 'function' ? subscriptions(this.props) : subscriptions,
(subscribe, prop) =>
subscribe(value => this.setState({ [prop]: value }))
)
}
componentWillUnmount () {
this._unsubscribes.forEach(call)
this._unsubscribes = null
}
render () {
return <Component {...this.props} {...this.state} />
}
}

View File

@ -35,6 +35,10 @@ export const EMPTY_OBJECT = Object.freeze({})
// ===================================================================
export addSubscriptions from './add-subscriptions'
// ===================================================================
export const ensureArray = value => {
if (value === undefined) {
return []
@ -57,48 +61,6 @@ export const propsEqual = (o1, o2, props) => {
// ===================================================================
// `subscriptions` can be a function if we want to ensure that the subscription
// callbacks have been correctly initialized when there are circular dependencies
export const addSubscriptions = subscriptions => Component => {
class SubscriptionWrapper extends BaseComponent {
constructor () {
super()
this._unsubscribes = null
}
componentWillMount () {
this._unsubscribes = map(
isFunction(subscriptions) ? subscriptions(this.props) : subscriptions,
(subscribe, prop) =>
subscribe(value => this._setState({ [prop]: value }))
)
}
componentDidMount () {
this._setState = this.setState
}
componentWillUnmount () {
forEach(this._unsubscribes, unsubscribe => unsubscribe())
this._unsubscribes = null
delete this._setState
}
_setState (nextState) {
this.state = { ...this.state, nextState }
}
render () {
return <Component {...this.props} {...this.state} />
}
}
return SubscriptionWrapper
}
// -------------------------------------------------------------------
export const checkPropsState = (propsNames, stateNames) => Component => {
const nProps = propsNames && propsNames.length
const nState = stateNames && stateNames.length