Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Call setState on React components once per dispatch #21

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"description": "React addons for nuclear-js",
"main": "build/index.js",
"scripts": {
"babel:watch": "NODE_ENV=production babel src -w --out-dir build",
"build": "scripts/build.sh",
"prepublish": "npm run build",
"test": "npm run lint && karma start --single-run",
Expand Down
38 changes: 19 additions & 19 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 @@ -41,8 +41,8 @@ export default function connect(mapStateToProps) {
}

updateState() {
let propMap = this.propMap
let stateToSet = {}
const propMap = this.propMap
const stateToSet = {}

for (let key in propMap) {
const getter = propMap[key]
Expand All @@ -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