Skip to content

Instantly share code, notes, and snippets.

@godjooyoung
Created July 25, 2023 05:52
Show Gist options
  • Save godjooyoung/66bcabdeb263e35ce568e5ab50516334 to your computer and use it in GitHub Desktop.
Save godjooyoung/66bcabdeb263e35ce568e5ab50516334 to your computer and use it in GitHub Desktop.
SSE를 통한 실시간 알림을 구현했습니다. 헤더에 토큰을 담기 위해 EventSourcePolyfill을 사용했습니다.
// 알람 창을 열었으면 신규 알람 아이콘 없앤다.
useEffect(() => {
if (isAlarmWindowOpen) {
console.log("[INFO] 알람 확인")
setIsNewNotification(0)
} else if (!isAlarmWindowOpen && isNewNotification === 0) {
//클린
dispatcher(__alarmClean())
}
}, [isAlarmWindowOpen])
useEffect(() => {
// [INFO] 알람 추가
setIsNewNotification(alarmInfo.length)
}, [alarmInfo])
useEffect(() => {
// 세션 스토리지에서 SSE 구독 상태를 확인
const isSubscribed = sessionStorage.getItem('isSubscribed');
if (isLogin && !isSubscribed) {
// 로그인 상태일때 최초 한번만 구독 실행
const subcribeSSE = async () => {
const accessKey = await getCookie('token')
const EventSource = EventSourcePolyfill
if (isLogin && accessKey && !isSubscribed) {
eventSourceRef.current = new EventSource(
//헤더에 토큰
`${process.env.REACT_APP_SERVER_URL}/sse/subscribe`,
{
headers: {
'ACCESS_KEY': accessKey,
},
withCredentials: true, // 토큰 값 전달을 위해 필요한 옵션
}
)
if (eventSourceRef.current.readyState === 1) {
// console.log("[INFO] SSE connection 상태")
}
eventSourceRef.current.addEventListener('open', (event) => {
sessionStorage.setItem('isSubscribed', true);
})
eventSourceRef.current.addEventListener('message', (event) => {
const data = event.data
if (data.indexOf('EventStream Created') === -1) {
console.log("[INFO] 알람 발생", data)
dispatcher(__alarmSender(data))
}
})
return () => {
if (eventSourceRef.current && !isLogin) {
sessionStorage.setItem('isSubscribed', false)
//dispatcher(__alarmClean())
eventSourceRef.current.close() // 로그아웃 시 SSE 연결 종료
}
};
}
};
subcribeSSE()
avataGenHandler()
}
}, [isLogin]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment