diff --git a/src/services/Common.ts b/src/services/Common.ts index 7bc06fc7ea..50bd9192f5 100644 --- a/src/services/Common.ts +++ b/src/services/Common.ts @@ -160,6 +160,23 @@ class CommonService { .get() ).docs.map((ref) => ref.ref.path.split("/")[1]); + public subscribeToUserCommonIds = ( + userId: string, + callback: (data: string[]) => void, + ): UnsubscribeFunction => { + const query = firebase + .firestore() + .collectionGroup(SubCollections.Members) + .where("userId", "==", userId); + + return query.onSnapshot((snapshot) => { + const userCommonIds = snapshot.docs.map( + (ref) => ref.ref.path.split("/")[1], + ); + callback(userCommonIds); + }); + }; + public getAllUserCommonMemberInfo = async ( userId: string, ): Promise<(CommonMember & { commonId: string })[]> => { diff --git a/src/shared/hooks/useCases/useUserCommonIds.ts b/src/shared/hooks/useCases/useUserCommonIds.ts index 573e9aff85..5b2fbd0ece 100644 --- a/src/shared/hooks/useCases/useUserCommonIds.ts +++ b/src/shared/hooks/useCases/useUserCommonIds.ts @@ -1,13 +1,11 @@ -import { useCallback, useEffect } from "react"; +import { useEffect } from "react"; import { useSelector } from "react-redux"; import { selectUser } from "@/pages/Auth/store/selectors"; -import { CommonService, Logger } from "@/services"; +import { CommonService } from "@/services"; import { LoadingState } from "@/shared/interfaces"; -import { useIsMounted } from "../useIsMounted"; import { useLoadingState } from "../useLoadingState"; export const useUserCommonIds = (): LoadingState => { - const isMounted = useIsMounted(); const user = useSelector(selectUser()); const userId = user?.uid; const [state, setState] = useLoadingState([], { @@ -15,8 +13,13 @@ export const useUserCommonIds = (): LoadingState => { fetched: !userId, }); - const fetchUserCommonIds = useCallback(async () => { + useEffect(() => { if (!userId) { + setState({ + loading: false, + fetched: true, + data: [], + }); return; } @@ -26,37 +29,18 @@ export const useUserCommonIds = (): LoadingState => { data: [], }); - let userCommonIds: string[] = []; - - try { - userCommonIds = await CommonService.getUserCommonIds(userId); - } catch (error) { - Logger.error(error); - } finally { - if (isMounted()) { + const unsubscribe = CommonService.subscribeToUserCommonIds( + userId, + (userCommonIds) => { setState({ loading: false, fetched: true, data: userCommonIds, }); - } - } - }, [userId]); + }, + ); - const setUserCommonIds = useCallback((ids: string[]) => { - setState({ - loading: false, - fetched: true, - data: ids, - }); - }, []); - - useEffect(() => { - if (userId) { - fetchUserCommonIds(); - } else { - setUserCommonIds([]); - } + return unsubscribe; }, [userId]); return {