@@ -15,6 +15,7 @@ export const useSSE = () => {
1515 const reconnectAttemptsRef = useRef ( 0 ) ; // 재연결 횟수 저장
1616
1717 useEffect ( ( ) => {
18+ let timeoutId : NodeJS . Timeout ;
1819 // 로그인 상태가 아니거나 토큰이 없으면 SSE 연결을 하지 않음
1920 if ( ! isAuthenticated || ! accessToken ) {
2021 console . log ( '로그아웃상태이거나 토큰이 없어서 SSE 연결을 해제합니다.' ) ;
@@ -23,17 +24,24 @@ export const useSSE = () => {
2324 }
2425
2526 const connectSSE = ( ) => {
27+ // 최대 재연결 횟수 초과 시 종료
2628 if ( reconnectAttemptsRef . current >= 3 ) {
2729 console . warn ( '🚫 SSE: 최대 재연결 횟수(3번) 초과, 더 이상 재연결하지 않습니다.' ) ;
2830 return ;
2931 }
3032
3133 console . log ( `🔌 SSE: 연결 시도 중... (재연결 횟수: ${ reconnectAttemptsRef . current } )` ) ;
3234
33- if ( eventSourceRef . current ) {
34- eventSourceRef . current . close ( ) ;
35+ // 기존 연결이 있다면 종료
36+ eventSourceRef . current ?. close ( ) ;
37+
38+ // 로그인 상태와 토큰을 한 번 더 검증
39+ if ( ! isAuthenticated || ! accessToken ) {
40+ console . log ( '⛔ SSE 연결 시도 중단: 로그아웃 상태거나 토큰 없음' ) ;
41+ return ;
3542 }
3643
44+ // SSE 연결
3745 eventSourceRef . current = new EventSourcePolyfill (
3846 `${ import . meta. env . VITE_API_URL } /api/alert/connect` ,
3947 {
@@ -84,7 +92,7 @@ export const useSSE = () => {
8492 console . warn (
8593 `⚠️ SSE: 재연결 시도 중... (남은 재연결 횟수: ${ 3 - reconnectAttemptsRef . current } )` ,
8694 ) ;
87- setTimeout ( connectSSE , 1000 ) ;
95+ timeoutId = setTimeout ( connectSSE , 1000 ) ;
8896 } else {
8997 console . error ( '🚫 SSE: 최대 재연결 횟수 초과. 더 이상 재연결하지 않습니다.' ) ;
9098 }
@@ -95,6 +103,7 @@ export const useSSE = () => {
95103
96104 return ( ) => {
97105 console . log ( '🔴 SSE: 연결 해제' ) ;
106+ clearTimeout ( timeoutId ) ;
98107 eventSourceRef . current ?. close ( ) ;
99108 } ;
100109 } , [ isAuthenticated , accessToken ] ) ;
0 commit comments