Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/MOVIEJOJO7/cat-talk into fe…
Browse files Browse the repository at this point in the history
…ature/#63
  • Loading branch information
LikeFireAndSky committed Nov 15, 2023
2 parents 320994b + 0678ecb commit cb3a53f
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 41 deletions.
54 changes: 37 additions & 17 deletions Components/Chat/ChatRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import React, { useEffect, useState } from 'react';
import { Socket } from 'socket.io-client';
import { Chat, Message, chatUsersObject } from '@/types';
import { Chat, Message, chatUsersObject, User } from '@/types';
import { DefaultEventsMap } from 'socket.io/dist/typed-events';
import ChatHeader from '@/Components/Chat/ChatHeader';
import RenderChats from '@/Components/Chat/RenderChats';
Expand All @@ -18,18 +18,10 @@ const ChatRoom = ({
privateValue: string;
accessToken: string;
}) => {
const initChatusers = {
id: '',
name: '',
users: [], // 속한 유저 정보
isPrivate: JSON.parse(privateValue),
latestMessage: null,
updatedAt: new Date(),
};

const [messages, setMessages] = useState<Message[]>([]);
const [newMessage, setNewMessage] = useState('');
const [chatUsers, setChatUsers] = useState<Chat>(initChatusers);
const [chatUsers, setChatUsers] = useState<User[]>([]);
const [chatName, setChatName] = useState('');

// 채팅 참여자 fetch, socket 이벤트 등록 (1회 동작)
useEffect(() => {
Expand All @@ -49,7 +41,8 @@ const ChatRoom = ({
const chatUsersObject: chatUsersObject = await res.json();
const chatUsers: Chat = chatUsersObject.chat;

setChatUsers(chatUsers);
setChatName(chatUsers.name);
setChatUsers(chatUsers.users);
};

fetchChatUsers();
Expand All @@ -63,6 +56,32 @@ const ChatRoom = ({
setMessages((prevMessages) => [...prevMessages, messageObject]);
});

socket.on('join', (responseData) => {
// console.log('join 이벤트 리슨');
// console.log('responseData: ', responseData);
// console.log('responseData.users: ', responseData.users);
// console.log('responseData.joiner: ', responseData.joiners);

setChatUsers([...chatUsers, ...responseData.users]);
socket.emit(
'message-to-server',
`${responseData.users[0]} 님이 입장하셨습니다.`,
);
});

socket.on('leave', (responseData) => {
// console.log('leave 이벤트 리슨');
// console.log('responseData: ', responseData);
// console.log('responseData.users: ', responseData.users);
// console.log('responseData.leaver: ', responseData.leaver);

setChatUsers([...chatUsers, ...responseData.users]);
socket.emit(
'message-to-server',
`${responseData.leaver} 님이 퇴장하셨습니다.`,
);
});

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

Expand All @@ -73,8 +92,10 @@ const ChatRoom = ({
return () => {
socket.off('message-to-client');
socket.off('messages-to-client');
socket.off('join');
socket.off('leave');
};
}, [accessToken, chatId, socket]);
}, [accessToken, chatId, chatUsers, socket]);

// 서버로 메시지 전송
const sendMessage = () => {
Expand All @@ -96,13 +117,12 @@ const ChatRoom = ({
<ChatHeader
socket={socket}
chatId={chatId}
chatName={chatUsers.name}
chatUsers={chatUsers.users.length}
chatName={chatName}
chatUsers={chatUsers.length}
/>

{privateValue === 'true' ? (
<>
{chatUsers.users.length === 2 || chatUsers.users.length === 1 ? (
{chatUsers.length === 2 || chatUsers.length === 1 ? (
<>
<p>1대1 채팅방 입니다.</p>
<RenderChats
Expand Down
8 changes: 3 additions & 5 deletions Components/Chat/RenderChats.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getCookie } from '@/Components/Login/Cookie';
import React, { useEffect, useRef } from 'react';
import { Chat, Message } from '@/types';
import { Message, User } from '@/types';
import Chats from '@/Components/Chat/Chats';

const RenderChats = ({
Expand All @@ -9,7 +9,7 @@ const RenderChats = ({
useModal,
}: {
messages: Message[];
chatUsers: Chat;
chatUsers: User[];
useModal: boolean;
}) => {
const myId = getCookie('userId');
Expand All @@ -32,9 +32,7 @@ const RenderChats = ({
<>
<ul>
{messages.map((message, index) => {
const myUser = chatUsers.users.find(
(user) => user.id === message.userId,
);
const myUser = chatUsers.find((user) => user.id === message.userId);

if (myUser) {
return (
Expand Down
7 changes: 4 additions & 3 deletions Components/Search/OpenChatModal.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
'use client';

import { Chat } from '@/types';
import { getCookie } from '@/Components/Login/Cookie';
import OpenChatText from './OpenChatText';
import Image from 'next/image';
import { useRouter } from 'next/navigation';

const OpenChatModal = ({ modalChat }: { modalChat: Chat }) => {
const TEXT_SIZE = 'text-2xl';
const router = useRouter();
const accessToken = getCookie('accessToken');

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const joinChat = async () => {
Expand All @@ -16,10 +18,9 @@ const OpenChatModal = ({ modalChat }: { modalChat: Chat }) => {
headers: {
'Content-Type': 'application/json',
serverId: process.env.NEXT_PUBLIC_SERVER_ID as string,
Authorization:
`Bearer ${process.env.NEXT_PUBLIC_ACCESSTOKEN}` as string,
Authorization: `Bearer ${accessToken}` as string,
},
body: JSON.stringify({ chatId: process.env.NEXT_PUBLIC_CHAT_ID }),
body: JSON.stringify({ chatId: modalChat.id }),
});

router.push(`/chat/${modalChat.id}?isPrivate=false`);
Expand Down
19 changes: 6 additions & 13 deletions app/error.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
'use client';

export default function GlobalError({
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
export default function GlobalError({ reset }: { reset: () => void }) {
return (
<html>
<body>
<div className="w-[668px] h-[1446px] bg-pink-300">
<div className="w-[524px] h-[365px] bg-white rounded-[67px]">
<h2>Something went wrong!</h2>
<button type="button" onClick={() => reset()}>
Try again
</button>
</body>
</html>
<button onClick={reset}>다시 시도하기</button>
</div>
</div>
);
}
8 changes: 5 additions & 3 deletions app/not-found.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import React from 'react';

const NotFound = () => {
return (
<div>
<h1>NotFound</h1>
<a href="/users">다시 가기 버튼</a>
<div className="w-[668px] h-[1446px] bg-pink-300">
<div className="w-[524px] h-[365px] bg-white rounded-[67px]">
<h2>Not Found</h2>
<a href="/users">다시 가기 버튼</a>
</div>
</div>
);
};
Expand Down
5 changes: 5 additions & 0 deletions public/crying_cat.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit cb3a53f

Please sign in to comment.