From a21a84e25a1ca9b537c10d858ba3abada4542beb Mon Sep 17 00:00:00 2001
From: Pavel Meyer <meyerpavel1207@gmail.com>
Date: Mon, 7 Oct 2024 11:17:15 +0300
Subject: [PATCH] CW-performance

Fixed subscription for DiscussionMessages
---
 .../useCases/useDiscussionMessagesById.ts     | 43 +++++++++++++++----
 1 file changed, 35 insertions(+), 8 deletions(-)

diff --git a/src/shared/hooks/useCases/useDiscussionMessagesById.ts b/src/shared/hooks/useCases/useDiscussionMessagesById.ts
index 7e6fc36d3..2dd45e70d 100644
--- a/src/shared/hooks/useCases/useDiscussionMessagesById.ts
+++ b/src/shared/hooks/useCases/useDiscussionMessagesById.ts
@@ -1,4 +1,4 @@
-import { useState, useCallback } from "react";
+import { useState, useCallback, useEffect, useRef } from "react";
 import { useDispatch, useSelector } from "react-redux";
 import { useDeepCompareEffect, useUpdateEffect } from "react-use";
 import { trace } from "firebase/performance";
@@ -100,6 +100,8 @@ export const useDiscussionMessagesById = ({
   const [discussionMessagesWithOwners, setDiscussionMessagesWithOwners] =
     useState<any>();
 
+  const unsubscribeRef = useRef<firebase.Unsubscribe | null>(null);
+
   useUpdateEffect(() => {
     if (discussionId) {
       setDiscussionMessagesWithOwners([]);
@@ -251,7 +253,7 @@ export const useDiscussionMessagesById = ({
       const fetchDiscussionMessagesTrace = trace(perf, 'fetchDiscussionMessages');
       fetchDiscussionMessagesTrace.start();
 
-      DiscussionMessageService.subscribeToDiscussionMessagesByDiscussionId(
+      unsubscribeRef.current = DiscussionMessageService.subscribeToDiscussionMessagesByDiscussionId(
         discussionId,
         lastVisible && lastVisible[discussionId],
         async (
@@ -268,16 +270,16 @@ export const useDiscussionMessagesById = ({
             ...prevVisible,
             [discussionId]: lastVisibleDocument,
           }));
-  
+
           const hasLastVisibleDocument = !!lastVisibleDocument?.data();
-  
+
           const discussionsWithText = await Promise.all(
             updatedDiscussionMessages.map(async (discussionMessage) => {
               const isUserDiscussionMessage =
                 checkIsUserDiscussionMessage(discussionMessage);
               const isSystemMessage =
                 checkIsSystemDiscussionMessage(discussionMessage);
-  
+
               const parsedText = await getTextFromTextEditorString({
                 userId,
                 ownerId: isUserDiscussionMessage
@@ -294,7 +296,7 @@ export const useDiscussionMessagesById = ({
                 onFeedItemClick,
                 onInternalLinkClick,
               });
-  
+
               return {
                 ...discussionMessage,
                 parsedText,
@@ -321,10 +323,35 @@ export const useDiscussionMessagesById = ({
         },
       );
       fetchDiscussionMessagesTrace.stop();
-    } catch(err) {
+    } catch (err) {
       setIsBatchLoading(false);
     }
-  },[discussionId, isEndOfList, state.loading, state.data, isBatchLoading, lastVisible, userId, users, directParent, getCommonPagePath, getCommonPageAboutTabPath, onUserClick, onFeedItemClick, onInternalLinkClick, dispatch]);
+  }, [
+    discussionId,
+    isEndOfList,
+    state.loading,
+    state.data,
+    isBatchLoading,
+    lastVisible,
+    userId,
+    users,
+    directParent,
+    getCommonPagePath,
+    getCommonPageAboutTabPath,
+    onUserClick,
+    onFeedItemClick,
+    onInternalLinkClick,
+    dispatch,
+  ]);
+
+  useEffect(() => {
+    // Cleanup subscription on unmount or when discussionId changes
+    return () => {
+      if (unsubscribeRef.current) {
+        unsubscribeRef.current();
+      }
+    };
+  }, [discussionId]);
 
   useDeepCompareEffect(() => {
     (async () => {