When I'm mounting, I add the event listener and when unmounting removing works fine. But what isn't working is when I don't have more rows in my database, I want to stop the fetch calls. It is not removing the event listener and that causes infinite fetches but it should be avoided.
componentDidMount() {
window.addEventListener("scroll", debounce(this.listenToScroll, 500), true)
}
componentWillUnmount() {
window.removeEventListener("scroll", this.listenToScroll, true)
}
loader = () => {
const { showLoader } = this.state
const { page, isLoading, count, data } = this.props.load
const noMoreResults = <h5>No More Results</h5>
const loader = !isLoading && count === data.length ? noMoreResults :
showLoader ?
<Loader
type="ThreeDots"
color="#00BFFF"
height={80}
width={80}
timeout={10000} //3 secs
/> : null
if (loader === noMoreResults) {
console.log("true") {/*I get inside here but it isn't removing the event listener?*/}
window.removeEventListener("scroll", this.listenToScroll, true)
}
return loader
}
listenToScroll() {
console.log("im inside!!")
if (window.innerHeight + window.pageYOffset >= (window.document.body.scrollHeight - 500)) {
this.setState({ page: this.state.page + 1, change: !this.state.change, showLoader: true })
}
}
The problem is that when you add the event listener on mount, you're using the debounce() method.
So you're not actually adding this.listenToScroll, but you're actually adding an entirely different function. (which you don't have a reference to).
Maybe you can use a variable to store the debounced version.
this.debouncedListener = debounce(listenToScroll, 500);
window.addEventListener("scroll", this.debouncedListener, true)
window.removeEventListener("scroll", this.debouncedListener, true)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.