Skip to content

Commit 29bf0ca

Browse files
committed
refactor: 채팅 배열 수정
1 parent 6fca2ba commit 29bf0ca

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

frontend/src/pages/ChatRoom.jsx

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ const ChatRoom = () => {
3838
const [isOwner, setIsOwner] = useState(false);
3939
const [roomData, setRoomData] = useState(null);
4040
const [deleteNotification, setDeleteNotification] = useState(null);
41+
const MAX_MESSAGES = 200;
4142

4243
// 초기화 상태를 하나로 통합하고 단계별로 관리
4344
const [initState, setInitState] = useState({
@@ -225,7 +226,6 @@ const ChatRoom = () => {
225226
const stompClientRef = useWebSocket({
226227
roomId: initState.isRoomValidated ? roomId : null,
227228
onMessageReceived: (received) => {
228-
// 서버에서 받은 메시지만을 로컬 상태에 추가/업데이트
229229
setMessages(prev => {
230230
// 동일한 messageId를 가진 메시지가 이미 존재하면 업데이트하고, 없으면 추가
231231
const updated = prev.some(m => m.messageId === received.messageId)
@@ -234,17 +234,22 @@ const ChatRoom = () => {
234234

235235
const sorted = [...updated].sort((a, b) => new Date(a.sendAt).getTime() - new Date(b.sendAt).getTime());
236236

237-
// 새 메시지가 추가되었을 때만 맨 아래로 스크롤
238-
// 현재 스크롤 위치가 거의 맨 아래에 있다면 스크롤, 아니면 유지
237+
// 메시지 개수 제한 (최신 메시지들만 유지)
238+
const limitedMessages = sorted.length > MAX_MESSAGES
239+
? sorted.slice(-MAX_MESSAGES) // 마지막 MAX_MESSAGES개만 유지
240+
: sorted;
241+
242+
// 기존 스크롤 로직
239243
if (messageContainerRef.current) {
240244
const { scrollTop, clientHeight, scrollHeight } = messageContainerRef.current;
241-
const isNearBottom = (scrollTop + clientHeight) >= (scrollHeight - 100); // 100px 여유
242-
// 새 메시지가 나(currentUser)의 메시지이거나, 스크롤이 거의 맨 아래에 있을 때만 스크롤
245+
const isNearBottom = (scrollTop + clientHeight) >= (scrollHeight - 100);
246+
243247
if (isNearBottom || received.senderId === currentUser?.userId) {
244248
scrollToBottom();
245249
}
246250
}
247-
return sorted;
251+
252+
return limitedMessages;
248253
});
249254
},
250255
onProfileUpdate: handleProfileUpdate,

0 commit comments

Comments
 (0)