Skip to content

Commit

Permalink
use subscription in useUserCommonIds use-case
Browse files Browse the repository at this point in the history
  • Loading branch information
andreymikhadyuk committed Nov 14, 2023
1 parent 2979a19 commit e7260f1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 30 deletions.
17 changes: 17 additions & 0 deletions src/services/Common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 })[]> => {
Expand Down
44 changes: 14 additions & 30 deletions src/shared/hooks/useCases/useUserCommonIds.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
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<string[]> => {
const isMounted = useIsMounted();
const user = useSelector(selectUser());
const userId = user?.uid;
const [state, setState] = useLoadingState<string[]>([], {
loading: false,
fetched: !userId,
});

const fetchUserCommonIds = useCallback(async () => {
useEffect(() => {
if (!userId) {
setState({
loading: false,
fetched: true,
data: [],
});
return;
}

Expand All @@ -26,37 +29,18 @@ export const useUserCommonIds = (): LoadingState<string[]> => {
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 {
Expand Down

0 comments on commit e7260f1

Please sign in to comment.