Skip to content

Commit

Permalink
fix: 웹소켓 커스텀훅 추상화 수정 (#228)
Browse files Browse the repository at this point in the history
  • Loading branch information
swkim12345 authored Nov 21, 2024
2 parents b57d819 + 12661ab commit c48471f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
23 changes: 13 additions & 10 deletions packages/frontend/src/pages/stock-detail/ChatPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
import type { ChatDataType, ChatDataResponse } from '@/sockets/types';
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { TextArea } from './components';
import { ChatMessage } from './components/ChatMessage';
import DownArrow from '@/assets/down-arrow.svg?react';
import { useSocketChat } from '@/sockets/chat';
import { socketChat } from '@/sockets/config';
import { useWebsocket } from '@/sockets/useWebsocket';

export const ChatPanel = () => {
const STOCK_ID = '005930';

const [chatData, setChatData] = useState<ChatDataType[]>();
const { socket: socketChat, isConnected } = useSocketChat({
stockId: STOCK_ID,
});

const socket = useMemo(() => {
return socketChat({ stockId: STOCK_ID });
}, [STOCK_ID]);

const { isConnected } = useWebsocket(socket);

const handleSendMessage = (message: string) => {
if (isConnected) {
socketChat.emit('chat', {
socket.emit('chat', {
room: STOCK_ID,
content: message,
});
Expand All @@ -30,13 +33,13 @@ export const ChatPanel = () => {
};

if (isConnected) {
socketChat.on('chat', handleChat);
socket.on('chat', handleChat);

return () => {
socketChat.off('chat', handleChat);
socket.off('chat', handleChat);
};
}
}, []);
}, [isConnected, socket]);

return (
<article className="flex flex-col gap-5 rounded-md bg-white p-7">
Expand Down
26 changes: 26 additions & 0 deletions packages/frontend/src/sockets/useWebsocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useEffect, useState } from 'react';
import { Socket } from 'socket.io-client';

export const useWebsocket = (socket: Socket) => {
const [isConnected, setIsConnected] = useState(socket.connected);

useEffect(() => {
const onConnect = () => {
setIsConnected(true);
};

const onDisconnect = () => {
setIsConnected(false);
};

socket.on('connect', onConnect);
socket.on('disconnect', onDisconnect);

return () => {
socket.off('connect', onConnect);
socket.off('disconnect', onDisconnect);
};
}, [socket]);

return { isConnected };
};

0 comments on commit c48471f

Please sign in to comment.