G
G
Gimir2020-02-10 09:27:39
JavaScript
Gimir, 2020-02-10 09:27:39

How to change the state 1 time when scrolling to the bottom of 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, but to update existing content.
I wrote a function that when scrolling to the end of the page, in theory, should update the state (useState hook) 1 time, and scroll to the top of the page. In fact, the state is updated several times. How to make it work properly? Maybe there are some best practices?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Maltsev, 2020-02-10
@Gimir

Enter a variable to determine the download status

var is_loading_page = false;

// в обработчике скролинга
if (is_loading_page) return false;
is_loading_page = true;

// в калбеке получения новой страницы (через AJAX например)
is_loading_page = false;

M
MamaLuyba, 2020-02-10
@MamaLuyba

most likely this happens because the event reacts to the scrolling of the wheel and, accordingly, because multiple scrolls will have the same window height values ​​- the and function will work multiple times. but it is not exactly.
you can try to remove the eventListener after the first operation, and when scrolling to the top of the page, add it again.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question