React infinite scroll component

Viewed 452

I am trying to make application similar to facebook. When I reach bottom of the page I am fetching more data from API. I am using React and Redux. Simplified code:

const detectBottomOfPage= () => {
    if((window.innerHeight + window.scrollY) > document.body.scrollHeight) {
        dispatch(bottomOfPage()); //increases scrollCount
    }
};

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

useEffect(() => {
    dispatch(fetchMoreData(scrollCount));
},[scrollCount]);

When i scroll down it works fine, and fetches data. (page increases in height). But when i refresh the page, it detects bottom of page multiple times. I tried to remove listener before refresh (beforeunload event) but it doesn't work properly after refresh. Any solution ?

1 Answers

Instead of fighting with all the different scrolling quirks, the sanest solution is to ratelimit how fast you can trigger the infinite scrolling.

One way to do it would be to update your effect with some state checking:

const [lastFetch, setLastFetch] = React.useState(0);
useEffect(() => {
    const now = Math.floor(Date.now()/3000);
    if (lastFetch < now) {
        dispatch(fetchMoreData(scrollCount));
        setLastFetch(now);
    }
},[scrollCount]);
Related