Skip to content

Commit eff9409

Browse files
authored
feat: sse 연결 오류 시 3초마다 다시 연결하도록 수정 (#495)
1 parent 2252f5e commit eff9409

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

src/ConnectSSE.tsx

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { useState } from 'react';
12
import toast from 'react-hot-toast';
23

34
import { QueryClient, useQueryClient } from '@tanstack/react-query';
@@ -14,6 +15,8 @@ import { Alarm, CrewAlarm, GameAlarm } from '@type/models';
1415
export const ConnectSSE = () => {
1516
const queryClient = useQueryClient();
1617
const loginInfo = useLoginInfoStore((state) => state.loginInfo);
18+
const [, set] = useState(new Date());
19+
const reconnectSSE = () => set(new Date());
1720

1821
useEventSource({
1922
subscribeUrl: `${import.meta.env.VITE_BASE_URL}/alarms/subscribe`,
@@ -38,7 +41,11 @@ export const ConnectSSE = () => {
3841
},
3942
],
4043
],
41-
onerror: (error) => console.log(error),
44+
onerror: (error) => {
45+
if ('status' in error && error.status === 500) {
46+
setTimeout(() => reconnectSSE(), 3000);
47+
}
48+
},
4249
});
4350

4451
return null;

src/hooks/useEventSource.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { useEffect } from 'react';
22

33
import { EventSourcePolyfill, NativeEventSource } from 'event-source-polyfill';
44

5-
import { useLoginInfoStore } from '@stores/loginInfo.store';
5+
import { useTokenStore } from '@stores/accessToken.store';
66

77
export const useEventSource = ({
88
subscribeUrl,
@@ -17,17 +17,17 @@ export const useEventSource = ({
1717
onmessage?: EventSourcePolyfill['onmessage'];
1818
onerror?: EventSourcePolyfill['onerror'];
1919
}) => {
20-
const loginInfo = useLoginInfoStore((state) => state.loginInfo);
20+
const accessToken = useTokenStore((state) => state.accessToken);
2121

2222
useEffect(() => {
23-
if (!loginInfo?.id) {
23+
if (!accessToken) {
2424
return;
2525
}
2626

2727
const EventSource = EventSourcePolyfill || NativeEventSource;
2828
const eventSource = new EventSource(subscribeUrl, {
2929
headers: {
30-
Authorization: `Bearer ${loginInfo.accessToken}`,
30+
Authorization: `Bearer ${accessToken}`,
3131
'Content-type': 'text/event-stream',
3232
},
3333
heartbeatTimeout: 1000 * 60 * 60 * 6,
@@ -43,5 +43,5 @@ export const useEventSource = ({
4343
return () => {
4444
eventSource.close();
4545
};
46-
}, [loginInfo, onmessage, onerror, subscribeUrl, eventListenerParameters]);
46+
}, [accessToken, onmessage, onerror, subscribeUrl, eventListenerParameters]);
4747
};

0 commit comments

Comments
 (0)