Skip to content

Commit

Permalink
✨ 입장/퇴장 메시지 수신 시 모각코 정보 리페칭
Browse files Browse the repository at this point in the history
- useChatting 훅에서 join/leave 조건을 판별하기 위한 userIdRef 선언
  • Loading branch information
js43o committed Dec 10, 2023
1 parent 4803c91 commit 9e974da
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export function Chatting({
participatedRef.current.nickname,
participatedRef.current.id,
);
leaveRoom();
resetChatItems();
participatedRef.current = undefined;
}
Expand All @@ -72,13 +73,7 @@ export function Chatting({
leaveRoom,
]);

useEffect(() => {
if (!userData) {
return;
}

return () => leaveRoom(userData.id);
}, [userData, leaveRoom]);
useEffect(() => () => leaveRoom(), [leaveRoom]);

if (!userData) {
return (
Expand Down
39 changes: 30 additions & 9 deletions app/frontend/src/hooks/useChatting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,18 @@ import {
ChatMessage,
StatusType,
} from '@morak/chat/src/interface/message.interface';
import { useQueryClient } from '@tanstack/react-query';

import { URL } from '@/constants';
import { queryKeys } from '@/queries';

const socketClient = new SocketClient(URL.SOCKET, URL.SOCKET_PATH);

export function useChatting(postId: string) {
const [chatItems, setChatItems] = useState<ChatMessage[]>([]);
const userIdRef = useRef<string | null>(null);
const lastDateRef = useRef<Date | null | undefined>(undefined);
const queryClient = useQueryClient();

const sendMessage = (message: string, userId: string) => {
socketClient.sendMessage({
Expand Down Expand Up @@ -82,29 +86,46 @@ export function useChatting(postId: string) {
() =>
socketClient.subscribeToChat(
(status: StatusType, msgs: ChatMessage[]) => {
if (status === 200) {
setChatItems((items) => [...items, ...msgs]);
if (status !== 200) {
return;
}

setChatItems((items) => [...items, ...msgs]);
if (msgs.length === 1 && msgs[0].messageType === 'notification') {
queryClient.invalidateQueries({
queryKey: queryKeys.mogaco.detail(postId).queryKey,
});
}
},
),
[],
[postId, queryClient],
);

const joinRoom = useCallback(
(userId: string, callback?: () => void) =>
(userId: string, callback?: () => void) => {
if (userIdRef.current) {
return;
}

userIdRef.current = userId;
socketClient.joinRoom({ user: userId, room: postId }, (status) => {
if (status === 200) {
subscribeToChat();
callback?.();
}
}),
});
},
[postId, subscribeToChat],
);

const leaveRoom = useCallback(
(userId: string) => socketClient.leaveRoom({ user: userId, room: postId }),
[postId],
);
const leaveRoom = useCallback(() => {
if (!userIdRef.current) {
return;
}

socketClient.leaveRoom({ user: userIdRef.current, room: postId });
userIdRef.current = null;
}, [postId]);

const resetChatItems = useCallback(() => {
setChatItems([]);
Expand Down

0 comments on commit 9e974da

Please sign in to comment.