Skip to content

Commit 647d3ea

Browse files
committed
fix: 서로 다른 엔드포인트에 대한 useSocket 훅 기능 구현
1 parent dfd27ea commit 647d3ea

5 files changed

Lines changed: 73 additions & 49 deletions

File tree

src/context/SocketProvider.tsx

Lines changed: 34 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,47 +2,55 @@ import { createContext, useContext, useEffect, useState } from 'react';
22

33
import { io, Socket } from 'socket.io-client';
44

5-
const SocketContext = createContext<Socket | null>(null);
5+
type SocketMap = { [endpoint: string]: Socket };
6+
7+
const SocketContext = createContext<SocketMap | null>(null);
68

79
export const SocketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
8-
const [socket, setSocket] = useState<Socket | null>(null);
10+
const [socketMap, setSocketMap] = useState<SocketMap>({});
911

1012
useEffect(() => {
11-
const newSocket = io(`${import.meta.env.VITE_NEW_API_URL}/socket/chatting`, {
12-
transports: ['websocket'],
13-
});
14-
setSocket(newSocket);
15-
16-
newSocket.on('connect', () => {
17-
console.log('connection is open');
13+
const endpoints = ['chatting', 'matching']; // 필요한 엔드포인트 추가
14+
const newSockets: SocketMap = {};
15+
16+
endpoints.forEach((endpoint) => {
17+
const socket = io(`${import.meta.env.VITE_NEW_API_URL}/socket/${endpoint}`, {
18+
transports: ['websocket'],
19+
});
20+
newSockets[endpoint] = socket;
21+
22+
socket.on('connect', () => {
23+
console.log(`${endpoint} connection is open`);
24+
});
25+
26+
socket.on('disconnect', (reason) => {
27+
console.log(`${endpoint} Disconnected from server:`, reason);
28+
});
29+
30+
socket.on('connect_error', (err) => {
31+
console.log(`${endpoint} connect error:`, err.message);
32+
});
1833
});
1934

20-
newSocket.on('disconnect', (reason) => {
21-
console.log('Disconnected from server:', reason);
22-
});
23-
24-
newSocket.on('connect_error', (err) => {
25-
console.log(err.message);
26-
});
35+
setSocketMap(newSockets);
2736

2837
return () => {
29-
newSocket.disconnect();
38+
Object.values(newSockets).forEach((socket) => socket.disconnect());
3039
};
3140
}, []);
3241

33-
// 소켓 설정이 완료되지 않은 경우 렌더링 방지
34-
// 채팅방에서 새로고침했을 때 오류 방지
35-
if (!socket) {
42+
if (!Object.keys(socketMap).length) {
3643
return null;
3744
}
3845

39-
return <SocketContext.Provider value={socket}>{children}</SocketContext.Provider>;
46+
return <SocketContext.Provider value={socketMap}>{children}</SocketContext.Provider>;
4047
};
4148

42-
export const useSocket = () => {
43-
const context = useContext(SocketContext);
44-
if (context === null) {
45-
throw new Error('useSocket must be used within a SocketProvider');
49+
// 엔드포인트를 인자로 받아 해당 소켓을 반환하는 훅
50+
export const useSocket = (endpoint = 'chatting') => {
51+
const socketMap = useContext(SocketContext);
52+
if (!socketMap || !socketMap[endpoint]) {
53+
throw new Error(`useSocket must be used within a SocketProvider with a valid endpoint (${endpoint})`);
4654
}
47-
return context;
55+
return socketMap[endpoint];
4856
};

src/pages/Chats/MatchingRoom/index.tsx

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { useNavigate } from 'react-router-dom';
33

44
import { MatchingData } from '@apis/matching/dto';
55
import { useSocket } from '@context/SocketProvider';
6+
import { getCurrentUserId } from '@utils/getCurrentUserId';
67

78
import Back from '@assets/arrow/left.svg';
89

@@ -20,21 +21,15 @@ const MatchingRoom: React.FC = () => {
2021
const [isScroll, setIsScroll] = useState(false);
2122
const chatWindowRef = useRef<HTMLDivElement>(null);
2223

24+
const currentUserId = getCurrentUserId();
2325
const nav = useNavigate();
24-
const socket = useSocket();
26+
const socket = useSocket('matching');
2527

2628
// 메시지 수신 시 아래로 스크롤 (스크롤 아래 고정)
2729
const scrollToBottom = (ref: React.RefObject<HTMLDivElement>) => {
2830
if (ref.current) ref.current.scrollIntoView();
2931
};
3032

31-
// 전체 매칭 불러오기 socket api
32-
const getAllMatchings = (data: MatchingData[]) => {
33-
setAllMatchings(data);
34-
setIsScroll(true);
35-
setIsLoading(false);
36-
};
37-
3833
// 채팅방 입장 시 스크롤 아래로 이동
3934
useEffect(() => {
4035
const messagesContainer = chatWindowRef.current?.parentElement;
@@ -55,8 +50,23 @@ const MatchingRoom: React.FC = () => {
5550
}, [allMatchings]);
5651

5752
useEffect(() => {
53+
// 전체 매칭 불러오기 socket api
54+
const getAllMatchings = ({ matching }: { matching: MatchingData[] }) => {
55+
console.log(allMatchings);
56+
setAllMatchings(matching);
57+
setIsScroll(true);
58+
setIsLoading(false);
59+
};
60+
61+
const getNewMatching = (data: MatchingData) => {
62+
console.log(data);
63+
};
64+
5865
if (socket) {
59-
socket.emit('getAllMatchings', getAllMatchings);
66+
socket.emit('getAllMatchings', { userId: currentUserId });
67+
socket.emit('getMatching', { userId: currentUserId });
68+
socket.on('matchings', getAllMatchings);
69+
socket.on('nextMatching', getNewMatching);
6070
}
6171

6272
return () => {
@@ -82,7 +92,7 @@ const MatchingRoom: React.FC = () => {
8292
) : (
8393
allMatchings.map((matching: MatchingData) => {
8494
// TODO: 매칭 상태에 따라 응답 버튼 렌더링
85-
return <MatchingMessage {...matching} />;
95+
return <MatchingMessage key={matching.id} {...matching} />;
8696
})
8797
)}
8898
<div ref={chatWindowRef} />

src/pages/Chats/RcvdMessage/styles.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ export const MessageBox = styled.div`
3030
display: flex;
3131
flex-direction: column;
3232
gap: 0.2rem;
33-
max-width: 75%;
33+
/* max-width: 75%; */
3434
margin-right: 0.5rem;
3535
`;
3636

src/pages/Chats/RecentChat/MatchingRoomItem/index.tsx

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ const MatchingRoomItem: React.FC<Partial<LatestMatchingData>> = ({ requestStatus
3838
}
3939
}, []);
4040

41+
console.log(requestStatus);
42+
4143
return (
4244
<MatchingRoomLayout onClick={handleMatchingRoomClick}>
4345
<UserImage src={'오딩이 프로필 이미지'} alt="user" />
@@ -46,13 +48,7 @@ const MatchingRoomItem: React.FC<Partial<LatestMatchingData>> = ({ requestStatus
4648
오딩이
4749
</StyledText>
4850
<LatestMessage $textTheme={{ style: 'caption2-regular' }} color={theme.colors.text.primary}>
49-
{!requestStatus
50-
? '매칭이 들어오면 오딩이가 알려줄게!'
51-
: requestStatus === 'pending'
52-
? '얘가 너 소개해 달래'
53-
: requestStatus === 'rejected'
54-
? 'ㅠㅠ 담에 더 좋은 애 소개해 줄게'
55-
: '한번 연락해 봐봐'}
51+
{requestStatus === 'pending' ? '얘가 너 소개받고 싶대' : '매칭이 들어오면 오딩이가 알려줄게!'}
5652
</LatestMessage>
5753
</LeftBox>
5854
<RightBox>

src/pages/Chats/RecentChat/index.tsx

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,11 @@ const RecentChat: React.FC = () => {
2020
const [chatRoomList, setChatRoomList] = useState<ChatRoomData[]>([]);
2121
const [latestMatching, setLatestMatching] = useState<LatestMatchingData | null>();
2222
const [isLoading, setIsLoading] = useState(true);
23-
const socket = useSocket();
2423
const currentUserId = getCurrentUserId();
2524

25+
const socket = useSocket();
26+
const matchingSocket = useSocket('matching');
27+
2628
useEffect(() => {
2729
// 채팅방 리스트 조회
2830
const getChatRooms = (data: ChatRoomData[]) => {
@@ -43,20 +45,28 @@ const RecentChat: React.FC = () => {
4345

4446
if (socket) {
4547
socket.emit('getChatRooms', { userId: currentUserId });
46-
socket.emit('getLatestMatching', { userId: currentUserId }, getLatestMatching);
47-
socket.on('getLatestMatching', getLatestMatching);
48-
socket.on('matchingNotFound', matchingNotFound);
4948
socket.on('chatRoomList', getChatRooms);
5049
}
5150

51+
if (matchingSocket) {
52+
matchingSocket.emit('getLatestMatching', { userId: currentUserId });
53+
matchingSocket.on('getLatestMatching', getLatestMatching);
54+
matchingSocket.on('matchingNotFound', matchingNotFound);
55+
}
56+
5257
// 이벤트 리스너 정리
5358
// 컴포넌트가 언마운트되면 더 이상 이벤트를 수신하지 않음
5459
return () => {
5560
if (socket) {
5661
socket.off('getChatRooms', getChatRooms);
5762
}
63+
64+
if (matchingSocket) {
65+
matchingSocket.off('getLatestMatching', getLatestMatching);
66+
matchingSocket.off('matchingNotFound', matchingNotFound);
67+
}
5868
};
59-
}, [socket]);
69+
}, [socket, matchingSocket]);
6070

6171
return (
6272
<>

0 commit comments

Comments
 (0)