Skip to content

Commit

Permalink
fix: ensure that component is mounted before calling setState (greg…
Browse files Browse the repository at this point in the history
  • Loading branch information
gregberge committed Dec 11, 2018
1 parent 7b62559 commit 77e7d24
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/createLoadable.js
Expand Up @@ -59,13 +59,25 @@ function createLoadable({ resolve = identity, render, onLoad }) {
}

componentDidMount() {
this.mounted = true

if (this.state.loading) {
this.loadAsync()
} else if (!this.state.error) {
this.triggerOnLoad()
}
}

componentWillUnmount() {
this.mounted = false
}

safeSetState(nextState, callback) {
if (this.mounted) {
this.setState(nextState, callback)
}
}

triggerOnLoad() {
if (onLoad) {
setTimeout(() => {
Expand Down Expand Up @@ -93,7 +105,7 @@ function createLoadable({ resolve = identity, render, onLoad }) {
ctor
.requireAsync(this.props)
.then(loadedModule => {
this.setState(
this.safeSetState(
{
result: resolve(loadedModule, { Loadable }),
loading: false,
Expand All @@ -102,7 +114,7 @@ function createLoadable({ resolve = identity, render, onLoad }) {
)
})
.catch(error => {
this.setState({ error, loading: false })
this.safeSetState({ error, loading: false })
})

return this.promise
Expand Down

0 comments on commit 77e7d24

Please sign in to comment.