Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fire 329 fe 소켓으로 채팅 주고받음 #69

Merged
merged 3 commits into from
Jul 21, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 40 additions & 39 deletions src/components/room/Chatting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,14 @@ export function Chat({ socket }) {
useEffect(() => {
socket.on('chatMessage', receiveMessage);
}, []);

useEffect(() => {
moveScrollToReceiveMessage();
}, [messages]);

const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (newMessage === '') return;
if (newMessage.trim() === '') return;
socket.emit('chatMessage', {
room: roomId,
sender: localStorage.getItem('uid'),
Expand All @@ -41,46 +46,42 @@ export function Chat({ socket }) {
}
}, []);

const receiveMessage = useCallback(
(receiveMsg) => {
if (!userList[receiveMsg.sender]) {
try {
const API_URL = process.env.REACT_APP_GET_USER_INFO as string;
axios.get(API_URL + receiveMsg.sender).then((res) => {
setUserList((users) => {
return { ...users, [receiveMsg.sender]: res.data };
});

setMessages((message) => [
...message,
{
uid: receiveMsg.sender,
nickname: res.data.nickname,
avatar: res.data.avatar,
message: receiveMsg.message,
creratedAt: receiveMsg.createdAt,
},
]);
const receiveMessage = useCallback((receiveMsg) => {
if (!userList[receiveMsg.sender]) {
try {
const API_URL = process.env.REACT_APP_GET_USER_INFO as string;
axios.get(API_URL + receiveMsg.sender).then((res) => {
setUserList((users) => {
return { ...users, [receiveMsg.sender]: res.data };
});
} catch (err) {
console.log('error!! ', err);
}
} else {
setMessages((message) => [
...message,
{
uid: receiveMsg.sender,
nickname: userList[receiveMsg.sender].nickname,
avatar: userList[receiveMsg.sender].avatar,
message: receiveMsg.message,
creratedAt: receiveMsg.createdAt,
},
]);

setMessages((message) => [
...message,
{
uid: receiveMsg.sender,
nickname: res.data.nickname,
avatar: res.data.avatar,
message: receiveMsg.message,
creratedAt: receiveMsg.createdAt,
},
]);
});
} catch (err) {
console.log('error!! ', err);
}
moveScrollToReceiveMessage();
},
[moveScrollToReceiveMessage],
);
} else {
setMessages((message) => [
...message,
{
uid: receiveMsg.sender,
nickname: userList[receiveMsg.sender].nickname,
avatar: userList[receiveMsg.sender].avatar,
message: receiveMsg.message,
creratedAt: receiveMsg.createdAt,
},
]);
}
}, []);

return (
<Component>
Expand Down