0

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]);

1 Answer 1

0

The problem is To scroll back to the new section after fetching data, you can use the scrollTo method. After fetching new data, calculate the difference between the new scroll height and the previous scroll height, and then scroll to that position. Example:

useEffect(() => {
  const currentTopMessageBoxRef = topMessageBoxRef.current;

  const handleScroll = async () => {
    const { scrollTop, scrollHeight } = currentTopMessageBoxRef;

    if (scrollTop < 200 && !isFetchingNextPage) {
      await fetchNextChatMessagesPage();
      const newScrollHeight = currentTopMessageBoxRef.scrollHeight;
      const scrollDifference = newScrollHeight - scrollHeight;
      currentTopMessageBoxRef.scrollTo(0, scrollDifference);
    }
  };

  if (currentTopMessageBoxRef) {
    currentTopMessageBoxRef.addEventListener('scroll', handleScroll);
  }

  return () => {
    if (currentTopMessageBoxRef) {
      currentTopMessageBoxRef.removeEventListener('scroll', handleScroll);
    }
  };
}, [fetchNextChatMessagesPage, isFetchingNextPage]);

To ensure that fetching occurs when the user scrolls to the top (scroll position 0), modify the condition in your handleScroll function. Instead of checking if scrollTop < 200, check if scrollTop === 0. This way, fetching will occur when the user reaches the top of the chat.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.