Skip to content

Commit

Permalink
feat: sse 연결 오류 시 3초마다 다시 연결하도록 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
dlwl98 committed Dec 4, 2023
1 parent 2252f5e commit 530a8d3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
9 changes: 8 additions & 1 deletion src/ConnectSSE.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useState } from 'react';
import toast from 'react-hot-toast';

import { QueryClient, useQueryClient } from '@tanstack/react-query';
Expand All @@ -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`,
Expand All @@ -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;
Expand Down
10 changes: 5 additions & 5 deletions src/hooks/useEventSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -43,5 +43,5 @@ export const useEventSource = ({
return () => {
eventSource.close();
};
}, [loginInfo, onmessage, onerror, subscribeUrl, eventListenerParameters]);
}, [accessToken, onmessage, onerror, subscribeUrl, eventListenerParameters]);
};

0 comments on commit 530a8d3

Please sign in to comment.