diff --git a/src/ConnectSSE.tsx b/src/ConnectSSE.tsx index f777c3bf..a4c9baa0 100644 --- a/src/ConnectSSE.tsx +++ b/src/ConnectSSE.tsx @@ -1,3 +1,4 @@ +import { useState } from 'react'; import toast from 'react-hot-toast'; import { QueryClient, useQueryClient } from '@tanstack/react-query'; @@ -14,6 +15,8 @@ import { Alarm, CrewAlarm, GameAlarm } from '@type/models'; export const ConnectSSE = () => { const queryClient = useQueryClient(); const loginInfo = useLoginInfoStore((state) => state.loginInfo); + const [, set] = useState(new Date()); + const reconnectSSE = () => set(new Date()); useEventSource({ subscribeUrl: `${import.meta.env.VITE_BASE_URL}/alarms/subscribe`, @@ -38,7 +41,11 @@ export const ConnectSSE = () => { }, ], ], - onerror: (error) => console.log(error), + onerror: (error) => { + if ('status' in error && error.status === 500) { + setTimeout(() => reconnectSSE(), 3000); + } + }, }); return null; diff --git a/src/hooks/useEventSource.ts b/src/hooks/useEventSource.ts index 9c34cda6..600eb878 100644 --- a/src/hooks/useEventSource.ts +++ b/src/hooks/useEventSource.ts @@ -2,7 +2,7 @@ import { useEffect } from 'react'; import { EventSourcePolyfill, NativeEventSource } from 'event-source-polyfill'; -import { useLoginInfoStore } from '@stores/loginInfo.store'; +import { useTokenStore } from '@stores/accessToken.store'; export const useEventSource = ({ subscribeUrl, @@ -17,17 +17,17 @@ export const useEventSource = ({ onmessage?: EventSourcePolyfill['onmessage']; onerror?: EventSourcePolyfill['onerror']; }) => { - const loginInfo = useLoginInfoStore((state) => state.loginInfo); + const accessToken = useTokenStore((state) => state.accessToken); useEffect(() => { - if (!loginInfo?.id) { + if (!accessToken) { return; } const EventSource = EventSourcePolyfill || NativeEventSource; const eventSource = new EventSource(subscribeUrl, { headers: { - Authorization: `Bearer ${loginInfo.accessToken}`, + Authorization: `Bearer ${accessToken}`, 'Content-type': 'text/event-stream', }, heartbeatTimeout: 1000 * 60 * 60 * 6, @@ -43,5 +43,5 @@ export const useEventSource = ({ return () => { eventSource.close(); }; - }, [loginInfo, onmessage, onerror, subscribeUrl, eventListenerParameters]); + }, [accessToken, onmessage, onerror, subscribeUrl, eventListenerParameters]); };