skip to Main Content
  const handleReadChat = useCallback(() => {
    const entry = refEntries.current;
    if (
      entry.scrollTop > entry.scrollHeight - 800 &&
      activeRoom &&
      conversations?.content?.length > 0 &&
      activeRoom.unread
    ) {
      setTimeout(() => {
        dispatch(readConversationByRoom(activeRoom.id));
        console.log("executed", activeRoom.unread);
      }, 3000);
    }
  }, [activeRoom, conversations?.content]);

  useEffect(() => {
    const entry = refEntries.current;
    const handleScrollButtonVisibility = () => {
      if (entry.scrollTop < entry.scrollHeight - 800) {
        setShowScrollButton(true);
      } else {
        setShowScrollButton(false);
      }
    };

    entry.addEventListener("scroll", handleScrollButtonVisibility);
    entry.addEventListener("scroll", handleReadChat);
    return () => {
      entry.removeEventListener("scroll", handleScrollButtonVisibility);
      entry.removeEventListener("scroll", handleReadChat);
    };
  }, [handleReadChat]);

So the code above I’m using for a chat app that I’m building, where if that room has unread messages, and if I scroll to the bottom of the page, it will trigger the handleReadChat function and set the read status to true. However, I noticed that when I scroll, it gets triggered as many times as how far I scrolled. I think if I scrolled 200px down, it will get triggered 200x. Is there a better way to refactor my code?

2

Answers


  1. You could use the scrollend event then within the callback check if the scroll is at the bottom of the page

    Login or Signup to reply.
  2. You could set a variable to limit the scroll using window.innerheight.

    Create an if statement that say when innerheight reaches 200 it will stop "rolling".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search