Answer the question
In order to leave comments, you need to log in
How to load posts as the page scrolls?
In componentDidMount, a scroller is hung on the window, if the page is scrolled almost to the end (the whole page is 200px), the method from the back (getAllNews) twitches, which returns posts, this method takes 2 parameters, how many posts to skip and how many to take from the full list of posts that lie on the back.
For example, if we initially load the first 3 posts, then this method twitches with parameters 0 (how many we skip) and 3 (how many posts we take), then when we scroll the page almost to the end, this method twitches again but with parameters 3 (how many we need to skip) and 3 (how much to take) and in parallel the local field in the state increases, which is responsible for how much to skip
Since setState is asynchronous, the getAllNews method can twitch with the same parameters if the user scrolls quickly, because it twitches on each scroll and if the state has not changed yet, then it sends the same requests
The question is, how to make it so that getAllNews does not was called until the setState from the previous scroll completes?
state = {
list: [],
skip: 5
};
componentDidMount() {
service
.getAllNews(0, 5)
.then((body) => {
this.setState(() => {
return {
list: body.newsSlims,
total: body.total,
};
});
})
.then(() => {
window.addEventListener("wheel", (e) => {
let windowBottom = document.documentElement.getBoundingClientRect()
.bottom;
if (
windowBottom < document.documentElement.clientHeight + 400 &&
this.state.total > this.state.skip
) {
service.getAllNews(this.state.skip, 5).then((body) => {
this.setState(() => {
return {
skip: this.state.skip + 5,
list: this.state.list.concat(body.newsSlims),
};
});
});
}
});
});
}
Answer the question
In order to leave comments, you need to log in
Set the flag (local private class variable), then in the scroll handler:
if (!this._allowInfinite) return;
this._allowInfinite = false;
// ...API call
// ...in then, after the call is complete
this._allowInfinite = true;
You don’t need to do everything through setState, and if you do, then for synchronization, see the callback in the setState function.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question