I have this app that when the user reaches near the bottom of the screen, new content will be fetched from the API in the infinity scroll method.
But if this user scrolls too fast or just keeps scrolling to the bottom while new content is being fetched, the function fires multiple time and this causes the app to get the same content twice and thus getting errors about react children having the same keys.
This is the functionality that detects when the user is near the bottom:
const [isFetching, setIsFetching] = useState(false);
// Fire Upon Reaching the Bottom of the Page
const handleScroll = () => {
if (
window.innerHeight +
Math.max(
window.pageYOffset,
document.documentElement.scrollTop,
document.body.scrollTop
) >
document.documentElement.offsetHeight - 100
) {
setIsFetching(true);
} else {
return;
}
};
// Debounce the Scroll Event Function and Cancel it When Called
const debounceHandleScroll = debounce(handleScroll, 500);
useEffect(() => {
window.addEventListener("scroll", debounceHandleScroll);
return () => window.removeEventListener("scroll", debounceHandleScroll);
}, [debounceHandleScroll]);
debounceHandleScroll.cancel();
And this is the functionality responsible for dispatching the action:
// Get More Posts
const loadMoreItems = useCallback(() => {
dispatch(getMorePosts(moreApiAddress));
setIsFetching(false);
}, [dispatch, moreApiAddress]);
useEffect(() => {
if (!isFetching) return;
loadMoreItems();
}, [isFetching, loadMoreItems]);
How can I stop the function from being called multiple times when the user scrolls too fast while content is being fetched?