feat(xo-web/addSubscriptions): support initial values
This commit is contained in:
parent
1c6aebf997
commit
9142a95f79
@ -1,20 +1,31 @@
|
||||
import React from 'react'
|
||||
import { map, mapValues, noop } from 'lodash'
|
||||
import { forOwn, map } from 'lodash'
|
||||
|
||||
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
|
||||
//
|
||||
// each subscription can be either a `subscribe` function or a `[subscribe, initialValue]` array
|
||||
const addSubscriptions = subscriptions => Component =>
|
||||
class SubscriptionWrapper extends React.PureComponent {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
|
||||
// provide all props since the beginning (better behavior with Freactal)
|
||||
this.state = mapValues(
|
||||
(this._subscribes = typeof subscriptions === 'function' ? subscriptions(props) : subscriptions),
|
||||
noop
|
||||
)
|
||||
const state = {}
|
||||
const subscribes = {}
|
||||
forOwn(typeof subscriptions === 'function' ? subscriptions(props) : subscriptions, (subscription, prop) => {
|
||||
if (typeof subscription === 'function') {
|
||||
subscribes[prop] = subscription
|
||||
state[prop] = undefined
|
||||
} else {
|
||||
subscribes[prop] = subscription[0]
|
||||
state[prop] = subscription[1]
|
||||
}
|
||||
})
|
||||
this.state = state
|
||||
this._subscribes = subscribes
|
||||
}
|
||||
|
||||
_unsubscribes = undefined
|
||||
|
Loading…
Reference in New Issue
Block a user