Skip to content

Commit

Permalink
[#54] 채팅 미리보기 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
Dormarble committed Apr 29, 2021
1 parent f90ff23 commit c7c3fe7
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 19 deletions.
18 changes: 9 additions & 9 deletions src/views/chat/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { StatusCodes } from 'http-status-codes';
import ChatMessage from './chatMessage';
import { getSocket } from '../../utils/socket';

export default function Chatroom({location}) {
export default function Chatroom({location, history}) {
const [chatRoom, setChatRoom] = useState({});
const [input, setInput] = useState('');
const [messages, setMessages] = useState([]);
Expand All @@ -17,10 +17,6 @@ export default function Chatroom({location}) {

const chatRoomId = queryString.parse(location.search).id;

if(chatRoom === null) {
return <Redirect to='/chatrooms' />;
}

const range = useRef({start: 0, end: 0});
const messageRef = useRef([]);
const readPointRef = useRef([]);
Expand Down Expand Up @@ -49,7 +45,7 @@ export default function Chatroom({location}) {
} else {
newMessages = messageRef.current.concat(message);
}
console.log(newMessages)

setMessages(newMessages);
messageRef.current = newMessages;

Expand Down Expand Up @@ -84,9 +80,10 @@ export default function Chatroom({location}) {

if(response.status !== StatusCodes.OK) {
setEmptyMsg('데이터를 불러오는데 실패했습니다.');
setChatRoom(null);
chatRoomRef.current = null;
return;

history.push('/chatrooms');

throw new Error();
}

setChatRoom(response.data);
Expand Down Expand Up @@ -133,6 +130,9 @@ export default function Chatroom({location}) {
userId: userId,
messageIdx: range.current.end
});
})
.catch(() => {
return;
});
}, []);

Expand Down
14 changes: 9 additions & 5 deletions src/views/chatrooms/chatroomList.jsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { Container, Typography } from '@material-ui/core';
import { Box, Container, Typography } from '@material-ui/core';

export default function ChatroomList({rooms}) {
export default function ChatroomList({rooms, onClick}) {

return (
<Container>
{rooms.map(room => <Chatroom key={room._id} info={room} />)}
{rooms.map(room => <Chatroom key={room.id} info={room} onClick={onClick} />)}
</Container>
);
}

function Chatroom({info}) {
function Chatroom({info, onClick}) {
const userId = window.localStorage.getItem('userID');
const participants = info.participants.filter(p => p._id !== userId)
.map(p => p.name)
.reduce((acc, cur) => acc + ' ' + cur);

return (
<Link to={`/chat?id=${info._id}`}>
<Link name={info.id} to={`/chat?id=${info.id}`} onClick={onClick}>
<Container>
<Typography>{ info.name }</Typography>
<Typography>{ participants }</Typography>
<Box>
<Typography>{ info.topMessage }</Typography>
<Typography>{ info.new }</Typography>
</Box>
</Container>
</Link>
);
Expand Down
69 changes: 64 additions & 5 deletions src/views/chatrooms/index.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useRef } from 'react';
import { Box, Container, Link, Typography } from '@material-ui/core';
import { Redirect } from 'react-router';
import { requestAPI, API_FIND_CHATROOMS } from '../../utils/api';
import { requestAPI, API_FIND_CHATROOMS, API_GET_MESSAGES } from '../../utils/api';
import { useRecoilState } from 'recoil';
import { chatroomState } from '../../states/Chatroom';
import { StatusCodes } from 'http-status-codes';
Expand All @@ -10,7 +10,27 @@ import { getSocket } from '../../utils/socket';

export default function Chatrooms() {
const [chatrooms, setChatrooms] = useRecoilState(chatroomState);
const chatroomsRef = useRef([]);

const socket = getSocket();

const onMessageEvent = (event) => {
console.log(event)
const newChatrooms = chatroomsRef.current.map(room => {
if(room.id === event.chatRoom) {
const newRoom = { ...room };
newRoom.new = room.new + 1;
newRoom.topMessage = event.content;

return newRoom;
}
return room;
});

setChatrooms(newChatrooms);
chatroomsRef.current = newChatrooms;
}

useEffect(() => {
const getChatrooms = async () => {
const response = await requestAPI(API_FIND_CHATROOMS());
Expand All @@ -19,21 +39,60 @@ export default function Chatrooms() {
alert(response.data.message);
return;
}
setChatrooms(response.data);

const promises = response.data.map(async room => {
const res = await requestAPI(API_GET_MESSAGES().setQuery({chatRoomId: room._id, start: -1, end: -1}));
let topMessage = '';
if(res.status === StatusCodes.OK && res.data.length === 1) {
topMessage = res.data[0].content;
}

return {
id: room._id,
participants: room.participants,
name: room.name,
new: 0,
topMessage: topMessage
};
})

const rooms = await Promise.all(promises);

console.log(rooms)
setChatrooms(rooms);
chatroomsRef.current = rooms;
};

getChatrooms();

socket.on('message', onMessageEvent);
}, []);

const onClickRoom = (e) => {
const chatRoomId = e.target.getAttribute('name');

const newChatrooms = chatroomsRef.current.map(room => {
if(room.id === chatRoomId) {
const newRoom = { ...room };
newRoom.new = 0;

return newRoom;
}
return room;
});

setChatrooms(newChatrooms);
chatroomsRef.current = newChatrooms;
}

if(!window.localStorage.getItem('userID')) {
return <Redirect to='/login' />;
}
const socket = getSocket();

return (
<Container>
<Typography>채팅방</Typography>
<ChatroomList rooms={chatrooms} />
<ChatroomList rooms={chatrooms} onClick={onClickRoom} />
</Container>
);
}

0 comments on commit c7c3fe7

Please sign in to comment.