11import { EventSourcePolyfill } from 'event-source-polyfill' ;
2- import { useEffect } from 'react' ;
2+ import { useEffect , useRef } from 'react' ;
33
44import useAuthStore from '@/stores/authStore' ;
55
66export const useServerSentEvents = ( ) => {
77 const accessToken = useAuthStore . getState ( ) . accessToken ;
8+ const sourceRef = useRef < EventSourcePolyfill | null > ( null ) ;
89
910 useEffect ( ( ) => {
10- if ( ! accessToken ) return console . log ( '구독 연결 실패' ) ;
11-
12- let source : EventSourcePolyfill | null = null ;
11+ if ( ! accessToken ) {
12+ console . log ( '로그인 정보 확인불가' ) ;
13+ return ;
14+ }
1315
1416 const connectSSE = ( ) => {
1517 try {
1618 console . log ( '구독 시작' ) ;
17- source = new EventSourcePolyfill ( `${ import . meta. env . VITE_API_URL } /api/notifications/sub` , {
18- headers : {
19- Authorization : `Bearer ${ accessToken } ` ,
19+ sourceRef . current = new EventSourcePolyfill (
20+ `${ import . meta. env . VITE_API_URL } /api/notifications/sub` ,
21+ {
22+ headers : {
23+ Authorization : `Bearer ${ accessToken } ` ,
24+ } ,
2025 } ,
21- } ) ;
26+ ) ;
2227
23- source . onmessage = ( payload ) => {
24- console . log ( payload ) ;
28+ sourceRef . current . onmessage = ( event ) => {
29+ console . log ( event ) ;
2530 console . log ( '알림 전송' ) ;
2631 } ;
2732
28- source . addEventListener ( 'notification' , ( event ) => {
29- console . log ( event ) ;
30- console . log ( '알림 전송 dd' ) ;
31- } ) ;
33+ // sourceRef.current .addEventListener('notification', (event) => {
34+ // console.log(event);
35+ // console.log('알림 전송 dd');
36+ // });
3237
33- source . onerror = ( error ) => {
38+ sourceRef . current . onerror = ( error ) => {
3439 console . log ( error ) ;
3540 console . log ( '에러 발생함' ) ;
36- source ?. close ( ) ;
41+ sourceRef . current ?. close ( ) ;
3742 // 재연결 로직 추가 가능
3843 setTimeout ( connectSSE , 5000 ) ; // 5초 후 재연결 시도
3944 } ;
@@ -45,7 +50,16 @@ export const useServerSentEvents = () => {
4550 connectSSE ( ) ;
4651
4752 return ( ) => {
48- source ?. close ( ) ;
53+ console . log ( '컴포넌트 언마운트로 인한 구독해제' ) ;
54+ closeSSE ( ) ;
4955 } ;
5056 } , [ accessToken ] ) ;
57+
58+ // 바깥으로 보낼 closeSSE 함수
59+ const closeSSE = ( ) => {
60+ sourceRef . current ?. close ( ) ;
61+ sourceRef . current = null ;
62+ } ;
63+
64+ return { closeSSE } ;
5165} ;
0 commit comments