How to change state 1 time when scrolling down the page?

const updateContent = throttle(() => {
 let updated = false;
 if ((window.scrollY + window.innerHeight) === document.body.clientHeight) {
 window.scrollTo({top: 0, behavior: 'instant'});
 setCurrentPage(prevPage => {
console.log('UPDATED!!!');
 return prevPage+1;
});
};
 }, 1000);
//--------------------
window.addEventListener('scroll', updateContent);


The task is to do something like pagination, but not to go to the next page and update already existing content.
I wrote a function that, when best personal Finance in the end of the page is supposed to update the state (useState hook) 1 time, and scroll to top of page. In fact, the state is updated several times. How to make it work as it should? Maybe there are some best practices?
April 7th 20 at 10:55
2 answers
April 7th 20 at 10:57
Solution
Enter a variable to determine the status of the download

var is_loading_page = false;

// in the handler of the scrolling
if (is_loading_page) return false;
is_loading_page = true;

// in kaveke receive a new page (via AJAX for example)
is_loading_page = false;
And so they did. From the beginning wanted to do it, but then I thought: would not it be too clumsy? And decided to ask the question knowing)
Final version:
const updateContent = throttle(() => {
 let updating = true;
 if (window.scrollY === 0) updating = true;
 if ((window.scrollY + window.innerHeight) === document.body.clientHeight) {
 if (updating) {
 window.scrollTo({top: 0, behavior: 'instant'});
 setCurrentPage(prevPage => {
console.log('UPDATED!!!');
 return prevPage+1;
});
 updating = false;
}
};
 }, 300);
- Johnson commented on April 7th 20 at 11:00
@Johnson, it's not always clumsy solution is not correct)) This is the most simple and reliable way. The only better updating = false kaveke to do setTimeout in a second (or half second), just in case)) - linwood_Denesik commented on April 7th 20 at 11:03
April 7th 20 at 10:59
most likely it is because the event responds to the scroll wheel and, accordingly, since some spins will have the same height values of the window function and will work out a few times. but this is not accurate.
you can try to remove the eventListener after the first operation, and when the best personal Finance in the beginning of the page - re-add.
Did as you said and it worked fine. But since I have a eventListener added to the hook useState, decided to make using the variable updating, like so:
const updateContent = throttle(() => {
 let updating = true;
 if (window.scrollY === 0) updating = true;
 if ((window.scrollY + window.innerHeight) === document.body.clientHeight) {
 if (updating) {
 window.scrollTo({top: 0, behavior: 'instant'});
 setCurrentPage(prevPage => {
console.log('UPDATED!!!');
 return prevPage+1;
});
 updating = false;
}
};
 }, 300);
- Johnson commented on April 7th 20 at 11:02

Find more questions by tags JavaScriptReact