简体   繁体   中英

Scroll to bottom of the page loadMore gets called more than once

I have a page where a list of profiles are shown and when the user scrolls to the bottom of the page, the query should load more data. The loadMore function works as expected but my error is in the listener as when the user scrolls to the bottom quickly, it gets called more than 5 times.

const listener = useCallback(() => {
    if (window.innerHeight + window.scrollY >= document.body.scrollHeight) {
      loadMore();
    }
  }, [loadMore]);

  useEffect(() => {
    window.addEventListener('scroll', listener);
    return () => window.removeEventListener('scroll', listener);
  }, [listener]);

This causes the same items in the new query to be shown as it sends the loadMore the same data.

When i slowly scroll it works. When I scroll to the bottom fast loads the same profiles 5 different times. Its in the if statement of the listener.

Are you using a mac computer? If you scroll to the bottom quickly using the mac mouse, it always stops after the fraction wears out which will keeps triggering the event when the scroll position is in your detect zone.

Use debounce

Here is a good explanation of how to use debounce to prevent quick repeated triggering in your code.

or

Use a variable and a timeout

// Set a variable that indicates the state of pulling profile
var pulling_data = false;

// Ignore if it's true, otherwise et to true when users scroll into your detect zone
if (pulling_data) return;

// An example of fetching data

Ajax({
    before() {
        pulling_data = true;
    }
}).then(res => {
    // Handles data
}).catch(err => {
    // Handles error
}).then(() => {
    let timer_id = setTimeout(() => {
        pulling_data = false;
    }, 1000); // 1 second
});

In above example, no matter how quickly users repeatedly trigger to pull profile data, it always run once and make the next request only available 1 second after the current request is completed. Of course you can change the timer or not to use the timer.

Use custom event to detect when the scroll is end

Here are some examples of creating detecting if the scrolling event ends. You can trigger your fetch when the event is fired.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM