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

Prevent React setState on unmounted Component #12

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
15 changes: 10 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,21 @@ import React, { Component } from 'react'
import { View, NativeMethodsMixin, Dimensions } from 'react-native'

exports.InViewPort = class extends Component {
isMounted = false
constructor(props) {
super(props)
this.state = { rectTop: 0, rectBottom: 0 }
}

componentDidMount() {
this.isMounted = true
if (!this.props.disabled) {
this.startWatching()
}
}

componentWillUnmount() {
this.isMounted = false
this.stopWatching()
}

Expand All @@ -37,11 +40,13 @@ exports.InViewPort = class extends Component {
return
}
this.myview.measure((x, y, width, height, pageX, pageY) => {
Copy link

Choose a reason for hiding this comment

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

Check also here that component is mounted before starting timeout (failsafe).

Copy link
Author

Choose a reason for hiding this comment

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

Technically it is already failsafe "startWatching" is called only in "componentDidMount" and "componentWillReceiveProps" these lifecycle methods are invoked after the component are mounted

Copy link

Choose a reason for hiding this comment

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

Being public methods they can be called from outside...

this.setState({
rectTop: pageY,
rectBottom: pageY + height,
rectWidth: pageX + width
})
if (this.isMounted) {
this.setState({
rectTop: pageY,
rectBottom: pageY + height,
rectWidth: pageX + width
})
}
})
this.isInViewPort()
}, this.props.delay || 100)
Expand Down