diff --git a/src/components/Main/CreateGameModal/index.tsx b/src/components/Main/CreateGameModal/index.tsx index 7a5f089c..922796ef 100644 --- a/src/components/Main/CreateGameModal/index.tsx +++ b/src/components/Main/CreateGameModal/index.tsx @@ -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"; @@ -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({ @@ -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}`); diff --git a/src/hooks/useSocket.ts b/src/hooks/useSocket.ts deleted file mode 100644 index 1943ed00..00000000 --- a/src/hooks/useSocket.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { useEffect } from "react"; -import { io } from "socket.io-client"; - -interface Message { - id: string; - text: string; - userId: string; - createdAt: Date; -} - -const useSocket = ( - chatId: string, - callback?: (messageObject: Message) => void, -) => { - const token = JSON.parse(localStorage.getItem("token") as string); - - // 소켓 연결 - const socket = io(`https://fastcampus-chat.net/chat?chatId=${chatId}`, { - extraHeaders: { - Authorization: `Bearer ${token.accessToken}`, - serverId: import.meta.env.VITE_APP_SERVER_ID, - }, - }); - - // 변화 감지 - useEffect(() => { - if (callback) { - socket.on("message-to-client", (messageObject) => { - callback(messageObject); - }); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [socket]); - // 메시지 보내기 - const sendMessage = (text: string) => { - socket.emit("message-to-server", text); - }; - - return sendMessage; -}; - -export default useSocket; diff --git a/src/pages/Example/index.tsx b/src/pages/Example/index.tsx index 4b49c319..dcd89069 100644 --- a/src/pages/Example/index.tsx +++ b/src/pages/Example/index.tsx @@ -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); @@ -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) === "*&^") { // 초대 상태 저장 @@ -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([]); + // 초대방 정보 데이터 const [roomData, setRoomData] = useState({ id: "", @@ -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, }); @@ -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(() => { @@ -148,7 +168,9 @@ 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; @@ -156,22 +178,22 @@ const Example = () => { 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 ( @@ -188,9 +210,9 @@ const Example = () => { {/* 벡엔드 rest api 통신 */}
- - - + + +
{/* 메시지 소켓 통신 */} @@ -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]); diff --git a/src/socket/socket.ts b/src/socket/socket.ts new file mode 100644 index 00000000..9d86793e --- /dev/null +++ b/src/socket/socket.ts @@ -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;