Skip to content

Commit

Permalink
Aggregate store changes and call setState only once on connected comp…
Browse files Browse the repository at this point in the history
…onents

Relates to optimizely/nuclear-js#195. For the connect
method, this change adds only one observer to the reactor per call as opposed
to adding a separate listener for each key returned by mapStateToProps.
  • Loading branch information
iansinnott committed Aug 4, 2016
1 parent 8ab5ec3 commit 010d252
Showing 1 changed file with 17 additions and 17 deletions.
34 changes: 17 additions & 17 deletions src/connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export default function connect(mapStateToProps) {
constructor(props, context) {
super(props, context)
this.reactor = props.reactor || context.reactor
this.unsubscribeFns = []
this.unsubscribeFn = null
this.updatePropMap(props)
}

Expand Down Expand Up @@ -53,26 +53,26 @@ export default function connect(mapStateToProps) {
}

subscribe() {
let propMap = this.propMap
for (let key in propMap) {
const getter = propMap[key]
const unsubscribeFn = this.reactor.observe(getter, val => {
this.setState({
[key]: val,
})
})
const propMap = this.propMap
const keys = Object.keys(propMap)
const getters = keys.map(k => propMap[k])

this.unsubscribeFns.push(unsubscribeFn)
}
// Add a final function to the getter to aggregate results in an array
getters.push((...vals) => vals)

this.unsubscribeFn = this.reactor.observe(getters, (vals) => {
const newState = vals.reduce((state, val, i) => {
state[keys[i]] = val
return state
}, {})

this.setState(newState)
})
}

unsubscribe() {
if (this.unsubscribeFns.length === 0) {
return
}

while (this.unsubscribeFns.length > 0) {
this.unsubscribeFns.shift()()
if (this.unsubscribeFn) {
this.unsubscribeFn()
}
}

Expand Down

0 comments on commit 010d252

Please sign in to comment.