Skip to content

Commit

Permalink
[fix]: useSocket 에서 useChat 로직 분리
Browse files Browse the repository at this point in the history
  • Loading branch information
VictoryJu committed Sep 18, 2024
1 parent e2b2173 commit a091751
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 41 deletions.
44 changes: 6 additions & 38 deletions src/hooks/socket/useSocket.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,17 @@
import { useAuthStore } from '@/stores/useAuthStore';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useEffect, useMemo } from 'react';
import { io } from 'socket.io-client';
import { ChatMessage } from '../api/types/chat';
import { useChatRoomMessages } from '../api/useChat';

const MAX_ACK_TIME = 10000;
const INITIAL_RETRY = 3;

/**
*
* @param path 소켓 url path
* @param chatRoomId 현재 접속한 채팅방의 id
* @returns socket: 소켓 객체 | messages: 채팅방 메세지 | sendMessage: 메세지 보내는 함수|
* @returns socket: 소켓 객체
*/
export const useSocket = (path: 'chat' = 'chat', chatRoomId: string) => {
export const useSocket = (path: 'chat' = 'chat') => {
const token = useAuthStore((state) => state.accessToken);
const { data: previousMessages } = useChatRoomMessages({
chatRoomId,
});

const [messages, setMessages] = useState<ChatMessage[]>(
previousMessages ? previousMessages.data : []
);

const socket = useMemo(() => {
if (!token) return null;
Expand All @@ -32,37 +22,15 @@ export const useSocket = (path: 'chat' = 'chat', chatRoomId: string) => {
},
ackTimeout: MAX_ACK_TIME,
retries: INITIAL_RETRY,
autoConnect: false,
port: 5000,
});
}, [token, path]);

useEffect(() => {
if (!socket) return;
socket.connect();
socket.emit('join', chatRoomId);

const handleReceiveMessage = (msg: ChatMessage[]) => {
setMessages((prevMessages) => [...prevMessages, ...msg]);
};

socket.on('receive', handleReceiveMessage);

return () => {
socket.off('receive', handleReceiveMessage);
socket.disconnect();
if (socket) socket.disconnect();
};
}, [chatRoomId, socket]);

const sendMessage = useCallback(
(message: object, senderUuid: string) => {
if (socket) {
const socketUniqueId = `${socket.id}-${senderUuid}`;
socket.emit('send', message, socketUniqueId);
}
},
[socket]
);
}, [socket]);

return { socket, messages, sendMessage };
return { socket };
};
47 changes: 47 additions & 0 deletions src/hooks/useChat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { useCallback, useEffect, useState } from 'react';
import { useChatRoomMessages } from './api/useChat';
import { ChatMessage } from './api/types/chat';
import { useSocket } from './socket/useSocket';

/**
*
* @param chatRoomId 현재 접속한 채팅방의 id
* @returns messages: 채팅방 메세지 | sendMessage: 메세지 보내는 함수
*/
export const useChat = (chatRoomId: string) => {
const { socket } = useSocket();
const { data: previousMessages } = useChatRoomMessages({
chatRoomId,
});

const [messages, setMessages] = useState<ChatMessage[]>(
previousMessages?.data || []
);

useEffect(() => {
if (!socket) return;
socket.emit('join', chatRoomId);

const handleReceiveMessage = (msg: ChatMessage[]) => {
setMessages((prevMessages) => [...prevMessages, ...msg]);
};

socket.on('receive', handleReceiveMessage);

return () => {
socket.off('receive', handleReceiveMessage);
};
}, [chatRoomId, socket]);

const sendMessage = useCallback(
(message: object, senderUuid: string) => {
if (socket) {
const socketUniqueId = `${socket.id}-${senderUuid}`;
socket.emit('send', message, socketUniqueId);
}
},
[socket]
);

return { messages, sendMessage };
};
5 changes: 2 additions & 3 deletions src/pages/Chat/ChatRoom/ChatRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import ArrowLeftTailIcon from '@/icons/icon/ArrowLeftTail';
import DotsVerticalIcon from '@/icons/icon/DotsVertical';
import { useLocation, useNavigate } from 'react-router';
import { useState } from 'react';
import { useSocket } from '@/hooks/socket/useSocket';
import { useAuthStore } from '@/stores/useAuthStore';
import { UploadIcon, CameraIcon } from '@/icons/icon';
import { useChat } from '@/hooks/useChat';

type ChatMessageType = 'TEXT' | 'IMAGE' | 'VIDEO';

Expand All @@ -17,8 +17,7 @@ const ChatRoom = () => {

const [chatMessageContent, setChatMessageContent] = useState('');

const { messages, sendMessage } = useSocket('chat', chatRoomId);
console.log(messages);
const { messages, sendMessage } = useChat(chatRoomId);

const [chatMessageType, setChatMessageType] =
useState<ChatMessageType>('TEXT');
Expand Down
13 changes: 13 additions & 0 deletions src/pages/Chat/ChatRoom/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Suspense } from 'react';
import ChatRoom from './ChatRoom';
import LoadingSpinner from '@/pages/Loading/LoadingSpinner';

const ChatRoomPage = () => {
return (
<Suspense fallback={<LoadingSpinner />}>
<ChatRoom />
</Suspense>
);
};

export default ChatRoomPage;

0 comments on commit a091751

Please sign in to comment.