I am building a chat application using the React query useInfiniteQuery for fetching the data as the user scrolls to the top.
I am having problems with scrolling the bar back to previous scroll height: I tried using state for previous scroll height, random useEffects, and userefs but nothing seems to work.
I can't find a solution for this problem on guides and tutorials on the Internet. Moreover when I scroll to the top (0) then it won't fetch any data until I use scroll again, so for example if I fetch page 1,2,3 and it is stuck on page four.
I was expecting whenever a fetch occurs to scroll back to new scroll height - previous scroll height (to the start of the new section)
useEffect(() => {
const currentTopMessageBoxRef = topMessageBoxRef.current;
const handleScroll = async () => {
const { scrollTop, scrollHeight } = currentTopMessageBoxRef;
if (scrollTop < 200 && !isFetchingNextPage) {
fetchNextChatMessagesPage();
}
};
if (currentTopMessageBoxRef) {
currentTopMessageBoxRef.addEventListener('scroll', handleScroll);
}
return () => {
if (currentTopMessageBoxRef) {
currentTopMessageBoxRef.removeEventListener('scroll', handleScroll);
}
};
}, [fetchNextChatMessagesPage, isFetchingNextPage]);