Skip to content
Merged

Dev #190

Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/shared/providers/AlertProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,29 @@ import { type PropsWithChildren, useEffect, useRef } from 'react';
import { createAlertSSE } from '@/api/sseClient';
import type { Alert } from '@/api/alertApi';
import { useAlertStore } from '@/shared/store/useAlertStore';
import { useAuthStore } from '@/domains/login/store/useAuthStore';

const AlertProvider = ({ children }: PropsWithChildren): JSX.Element => {
const addAlert = useAlertStore((state) => state.addAlert);
const connectionRef = useRef<ReturnType<typeof createAlertSSE> | null>(null);
const addAlertRef = useRef(addAlert);
const accessToken = useAuthStore((state) => state.accessToken);
const authenticated = useAuthStore((state) => state.authenticated);

useEffect(() => {
addAlertRef.current = addAlert;
}, [addAlert]);

useEffect(() => {
// 토큰이 없거나 인증되지 않은 상태에서는 SSE를 유지하지 않음
if (!authenticated || !accessToken) {
if (connectionRef.current) {
connectionRef.current.close();
connectionRef.current = null;
}
return;
}

const connection = createAlertSSE<Alert>({
onMessage: (alert) => {
addAlertRef.current(alert);
Expand All @@ -31,7 +43,7 @@ const AlertProvider = ({ children }: PropsWithChildren): JSX.Element => {
connection.close();
connectionRef.current = null;
};
}, []);
}, [accessToken, authenticated]);

return <>{children}</>;
};
Expand Down
Loading