Skip to content

Commit

Permalink
fix: ensure that component is mounted before calling setState (#184)
Browse files Browse the repository at this point in the history
Closes #180
  • Loading branch information
gregberge authored Dec 11, 2018
1 parent e974933 commit fe0f47f
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions packages/component/src/createLoadable.js
Original file line number Diff line number Diff line change
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

2 comments on commit fe0f47f

@linkenneth
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this safe? If the component isn't mounted at time of require complete, this would cause the InnerLoadable to be indefinitely un-loaded, right?

@gregberge
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nop, it is safe, at each remount the state is reset so there is no problem.

Please sign in to comment.