Skip to content

Commit

Permalink
Merge pull request #80 from MOVIEJOJO7/Feature/#79
Browse files Browse the repository at this point in the history
Fix: Socket 이전메시지 버그 해결
  • Loading branch information
JitHoon authored Nov 16, 2023
2 parents 0557753 + 56f5ee2 commit 0e2a92a
Showing 1 changed file with 45 additions and 18 deletions.
63 changes: 45 additions & 18 deletions Components/Chat/ChatRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const ChatRoom = ({
const [chatUsers, setChatUsers] = useState<User[]>([]);
const [chatName, setChatName] = useState('');

// 채팅 참여자 fetch, socket 이벤트 등록 (1회 동작)
// 채팅 참여 유저 블러오기
useEffect(() => {
const fetchChatUsers = async () => {
const res = await fetch(
Expand All @@ -47,51 +47,78 @@ const ChatRoom = ({
};

fetchChatUsers();
}, [accessToken, chatId]);

socket.on('connect', () => {
socket.on('messages-to-client', (responseData) => {
setMessages(responseData.messages);
// 'fetch-messages' 이벤트 등록
useEffect(() => {
if (socket?.connected) {
socket.emit('fetch-messages');

socket.on('messages-to-client', (messagesObject) => {
setMessages(messagesObject.messages);
});
}

return () => {
socket?.off('messages-to-client');
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [socket.connected]);

socket.on('message-to-client', (messageObject) => {
setMessages((prevMessages) => [...prevMessages, messageObject]);
// message-to-client 이벤트 등록
useEffect(() => {
if (socket?.connected) {
socket.on('message-to-client', (responseData) => {
setMessages((prevMessages) => [...prevMessages, responseData]);
});
}

return () => {
socket?.off('message-to-client');
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [socket.connected]);

// join 이벤트 등록
useEffect(() => {
if (socket?.connected) {
socket.on('join', (responseData) => {
setChatUsers([...chatUsers, ...responseData.users]);
socket.emit(
'message-to-server',
`${responseData.users[0]} 님이 입장하셨습니다.`,
);
});
}

return () => {
socket.off('join');
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chatUsers, socket.connected]);

// leave 이벤트 등록
useEffect(() => {
if (socket?.connected) {
socket.on('leave', (responseData) => {
setChatUsers([...chatUsers, ...responseData.users]);
socket.emit(
'message-to-server',
`${responseData.leaver} 님이 퇴장하셨습니다.`,
);
});

socket.emit('fetch-messages');
});

socket.on('connect_error', (error) => {
throw error;
});
}

return () => {
socket.off('message-to-client');
socket.off('messages-to-client');
socket.off('join');
socket.off('leave');
};
}, [accessToken, chatId, chatUsers, socket]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chatUsers, socket.connected]);

// 서버로 메시지 전송
const sendMessage = () => {
if (newMessage.trim() !== '') {
socket.emit('message-to-server', newMessage);
socket?.emit('message-to-server', newMessage);
setNewMessage('');
}
};
Expand Down

0 comments on commit 0e2a92a

Please sign in to comment.