Skip to content

Commit

Permalink
Merge pull request #28 from pepero-1/feature/#1
Browse files Browse the repository at this point in the history
초대 팝업 소켓 통신 코드 수정, 메시지 중복 문제 해결, 소켓 연결 모듈화(useSocket 제거)
  • Loading branch information
suyeonnnnnnn authored Nov 11, 2023
2 parents 751f157 + e892bbb commit dad6490
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 111 deletions.
6 changes: 3 additions & 3 deletions src/components/Main/CreateGameModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import styled from "styled-components";
import useFetch from "../../../hooks/useFetch";
import useFireFetch from "../../../hooks/useFireFetch";
import useInput from "../../../hooks/useInput";
import useSocket from "../../../hooks/useSocket";
import connect from "../../../socket/socket";
import Loader from "../../common/Loader";
import UserCard from "../../common/UserCard";

Expand Down Expand Up @@ -175,7 +175,7 @@ const CreateGameModal = ({ setModal }: Props) => {
const token = JSON.parse(localStorage.getItem("token") as string);

// 소켓 연결
const sendMessage = useSocket("9fe8a1af-9c60-4937-82dd-21d6da5b9cd9");
const socket = connect("9fe8a1af-9c60-4937-82dd-21d6da5b9cd9");

// 게임 데이터
const [roomData, setRoomData] = useState<ChatRoom>({
Expand Down Expand Up @@ -289,7 +289,7 @@ const CreateGameModal = ({ setModal }: Props) => {
const text = JSON.stringify(inviteUser);

// 초대 메시지 전달
sendMessage(text);
socket.emit("message-to-server", text);

// 해당 게임방으로 이동
navigate(`/game?gameId=${createGame.result.id}`);
Expand Down
42 changes: 0 additions & 42 deletions src/hooks/useSocket.ts

This file was deleted.

114 changes: 48 additions & 66 deletions src/pages/Example/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ import ToastNotice from "../../components/common/ToastNotice";
import useFetch from "../../hooks/useFetch";
import useFireFetch from "../../hooks/useFireFetch";
import useInput from "../../hooks/useInput";
import useSocket from "../../hooks/useSocket";
import connect from "../../socket/socket";

interface MessageInfo {
id: string;
text: string;
}

const Example = () => {
const token = JSON.parse(localStorage.getItem("token") as string);
Expand All @@ -22,9 +27,10 @@ const Example = () => {
});

// 소켓 통신
const sendMessage = useSocket(
"9fe8a1af-9c60-4937-82dd-21d6da5b9cd9",
(messageObject) => {
const socket = connect("9fe8a1af-9c60-4937-82dd-21d6da5b9cd9");

useEffect(() => {
socket.on("message-to-client", (messageObject) => {
// 일반 채팅인지 초대 메시지인지 구별
if (messageObject.text.slice(-5, -2) === "*&^") {
// 초대 상태 저장
Expand All @@ -38,19 +44,34 @@ const Example = () => {
setRoomData(room);
} else {
// 메시지 데이터, 작성 유저 상태 저장
const copy = { ...message };
copy.id = messageObject.userId;
copy.text = messageObject.text;
setMessage(copy);
const message = {
id: messageObject.userId,
text: messageObject.text,
};

console.log(message);
setMessages((prev) => [...prev, message]);
}
},
);
});

// 채팅 기록 확인
socket.on("messages-to-client", (messageObject) => {
console.log(messageObject);
});

// 초대 메시지
socket.on("new-chat", (messageObject) => {
console.log(messageObject);
});

return () => {
socket.off("message-to-client");
};
}, [socket]);

// 메세지 데이터
const [message, setMessage] = useState({
id: "",
text: "",
});
const [messages, setMessages] = useState<MessageInfo[]>([]);

// 초대방 정보 데이터
const [roomData, setRoomData] = useState({
id: "",
Expand Down Expand Up @@ -84,7 +105,7 @@ const Example = () => {
url: "https://fastcampus-chat.net/chat/leave",
method: "PATCH",
data: {
chatId: "e6d8fd5b-00e3-4598-b826-11366c8c4676",
chatId: "535add19-c98f-4a9b-bc6f-c145c496cb91",
},
start: false,
});
Expand All @@ -94,9 +115,8 @@ const Example = () => {

// 메시지 값 변화시(소켓 통신 시) 콘솔에 메시지 데이터 출력
useEffect(() => {
if (message.id !== "") console.log(message);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [message.text]);
console.log(messages);
}, [messages]);

//팝업 변화 감지
useEffect(() => {
Expand Down Expand Up @@ -148,30 +168,32 @@ const Example = () => {
body: "updated",
createdAt: serverTimestamp(),
};

fireFetch.updateData("notice", "asdasdasdasdasd", newData);

const copy = [...notice.data];
const index = copy.findIndex((v) => v.id === "asdasdasdasdasd");
copy[index] = newData;

notice.setData(copy);
};

const postData_A = () => {
console.log(1);
const getMessages = () => {
socket.emit("fetch-messages");
};

const deleteData_A = () => {
const liveChat = () => {
live.refresh();
};

// api get 요청으로 가져온 데이터 출력
const getData_A = () => {
const getFetchData = () => {
console.log(users.result, users.loading, users.statusCode);
};

// 메시지 보내는 함수
const submitMessage = () => {
sendMessage(messageValue.value);
socket.emit("message-to-server", messageValue.value);
};

return (
Expand All @@ -188,9 +210,9 @@ const Example = () => {

{/* 벡엔드 rest api 통신 */}
<div style={{ marginBottom: "2rem" }}>
<Button onClick={postData_A}>Post</Button>
<Button onClick={deleteData_A}>나가기</Button>
<Button onClick={getData_A}>Get</Button>
<Button onClick={getMessages}>채팅 메시지 기록 확인</Button>
<Button onClick={liveChat}>나가기</Button>
<Button onClick={getFetchData}>Get</Button>
</div>

{/* 메시지 소켓 통신 */}
Expand All @@ -215,43 +237,3 @@ const Example = () => {
};

export default Example;

// // 채팅 서버 연결
// const socket = io(
// `https://fastcampus-chat.net/chat?chatId=9fe8a1af-9c60-4937-82dd-21d6da5b9cd9`,
// {
// extraHeaders: {
// Authorization: `Bearer ${token.accessToken}`,
// serverId: import.meta.env.VITE_APP_SERVER_ID,
// },
// },
// );

// // 소켓 통신 시 메시지 데이터 저장
// useEffect(() => {
// socket.on("message-to-client", (messageObject) => {
// // 일반 채팅인지 초대 메시지인지 구별

// if (messageObject.text.slice(-5, -2) === "*&^") {
// // 초대 상태 저장
// const usersArr = JSON.parse(messageObject.text);
// const users = [...usersArr];
// users.pop();
// users.pop();
// const room = usersArr[usersArr.length - 2];

// setToastUser(users);
// setRoomData(room);
// } else {
// // 메시지 데이터, 작성 유저 상태 저장
// const copy = { ...message };
// copy.id = messageObject.userId;
// copy.text = messageObject.text;
// setMessage(copy);
// }

// // console.log(messageObject);
// });

// // eslint-disable-next-line react-hooks/exhaustive-deps
// }, [socket]);
21 changes: 21 additions & 0 deletions src/socket/socket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { io } from "socket.io-client";

const connect = (chatId: string) => {
const token = JSON.parse(localStorage.getItem("token") as string);

const socket = io(
`https://fastcampus-chat.net/${
chatId === "main" ? "server" : `chat?chatId=${chatId}`
}`,
{
extraHeaders: {
Authorization: `Bearer ${token.accessToken}`,
serverId: import.meta.env.VITE_APP_SERVER_ID,
},
},
);

return socket;
};

export default connect;

0 comments on commit dad6490

Please sign in to comment.