Skip to content

Commit 8a46297

Browse files
authored
Small fixes (#10)
- fixed possible memory leak - fixed possible missing subscription bug - fixed bug of updating the state of an unmounted component
1 parent f74346f commit 8a46297

File tree

3 files changed

+17
-5
lines changed

3 files changed

+17
-5
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@umbrellio/observable",
3-
"version": "1.3.1",
3+
"version": "1.3.2",
44
"description": "Observable library",
55
"repository": "git@github.com:umbrellio/observable.git",
66
"author": "Aleksei Bespalov <nulldefiner@gmail.com>",

src/multipleObserver.js

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,27 @@
11
import React from "react"
22

33
const multipleObserver = stores => WrappedComponent => {
4+
const reduceStates = stores => {
5+
return stores.reduce((acc, { key, store }) => ({ ...acc, [key]: { ...store.getState() } }), {})
6+
}
7+
48
return class extends React.Component {
59
static displayName = `${stores.map(s => s.key).join(" ")} State Observer`
610

7-
state = stores.reduce((acc, { key, store }) => ({ ...acc, [key]: { ...store } }), {})
11+
state = reduceStates(stores)
812
mounted = false
913

1014
componentDidMount () {
1115
this.mounted = true
1216
this.unsubscribes = stores.map(({ key, store }) => store.subscribe(data => {
1317
this.mounted && this.setState({ [key]: data })
1418
}))
19+
this.setState(reduceStates(stores))
1520
}
1621

1722
componentWillUnmount () {
1823
this.unsubscribes.forEach(fn => fn())
24+
this.unsubscribes = []
1925
this.mounted = false
2026
}
2127

src/observer.js

+9-3
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,20 @@ const observer = (store, { key, map }) => WrappedComponent => {
55
static displayName = `${key} State Observer`
66

77
state = { ...store.getState() }
8+
mounted = false
89

9-
constructor (props) {
10-
super(props)
11-
this.unsubscribe = store.subscribe(data => this.setState(data))
10+
componentDidMount () {
11+
this.mounted = true
12+
this.unsubscribe = store.subscribe(data => {
13+
this.mounted && this.setState(data)
14+
})
15+
this.setState({ ...store.getState() })
1216
}
1317

1418
componentWillUnmount () {
1519
this.unsubscribe()
20+
this.unsubscribe = null
21+
this.mounted = false
1622
}
1723

1824
render () {

0 commit comments

Comments
 (0)