I am building this webapp with React, in which there is a page with posts. I am trying to implement Infinite Scroll functionality manually and it seems to be working only one time.
When I have the last element on my window, it calls the api to fetch more posts, but when I update the state and get to "new" last post, it doesn't fetch any more posts. I believe I am really close to fixing this but I need a little guidance from you guys.
Thanks in advance
Here is my code
this.props.getPosts(this.state.page); //for the first load of the page
this.scrollListener = window.addEventListener('scroll', (e) => {
this.handleScroll(e)
})
handleScroll = (e) => {
let loadMoreElement = document.querySelector('.postGrid > div:last-child');
var rect = loadMoreElement.offsetTop + loadMoreElement.clientHeight;
var pageOffset = window.pageYOffset + window.innerHeight + 200;
if(pageOffset > rect && !finished && !this.state.loading) {
this.loadMore()
this.props.getPosts(this.state.page)
if(!this.state.has_more){ //has_more it's been set by the API when you get to the last page
finished = true
console.log("done")
}
} else if (finished){
console.log("done")
}}
loadMore = () => {
this.setState((prevState) => ({
page: prevState.page + 1,
loading: true,
}))}
You are setting loading
to true in your loadMore
method, but one of the conditions to call loadMore
again is if the loading
is false ( !this.state.loading
)
You will need to set loading
to false again at some point ( if there is api calls involved ) or just skip the loading:true
part if you work with local data.
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.