Skip to content
Merged
Show file tree
Hide file tree
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
40 changes: 20 additions & 20 deletions src/components/common/header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ import loadingImg from '../../../assets/loadingImg.svg';
import { useModal } from '../../../hooks/useModal';
import Modal from '../modal/Modal';
import { formatImgPath } from '../../../util/formatImgPath';
// import bell from '../../../assets/bell.svg';
// import Notification from './Notification/Notification';
// import bellLogined from '../../../assets/bellLogined.svg';
// import { useEffect } from 'react';
// import { testLiveAlarm } from '../../../api/alarm.api';
import bell from '../../../assets/bell.svg';
import Notification from './Notification/Notification';
import bellLogined from '../../../assets/bellLogined.svg';
import { useMyProfileInfo } from '../../../hooks/user/useMyInfo';
import { useNotificationContext } from '../../../context/SseContext';
import { useEffect } from 'react';
import { testLiveAlarm } from '../../../api/alarm.api';
import { ROUTES } from '../../../constants/routes';

function Header() {
Expand All @@ -26,24 +27,26 @@ function Header() {
const isLoggedIn = useAuthStore((state) => state.isLoggedIn);
const { myData, isLoading } = useMyProfileInfo();

const { signalData, clearSignal } = useNotificationContext();

const handleClickLogout = () => {
userLogout();
useAuthStore.persist.clearStorage();
localStorage.clear();
};

// const { signalData, setSignalData } = useNotification();

// useEffect(() => {
// testLiveAlarm();
// }, []);

const profileImg = myData?.profileImg
? `${import.meta.env.VITE_APP_IMAGE_CDN_URL}/${formatImgPath(
myData.profileImg
)}?w=86&h=86&fit=crop&crop=entropy&auto=format,enhance&q=60`
: DefaultImg;

useEffect(() => {
if (process.env.NODE_ENV === 'deployment') {
testLiveAlarm();
}
}, []);

return (
<S.HeaderContainer>
<Link to={ROUTES.main}>
Expand All @@ -58,26 +61,23 @@ function Header() {
<S.HeaderLink>공지사항</S.HeaderLink>
</Link>
</S.HeaderLinkContainer>
{/* <S.Alarm role='button' tabIndex={0} aria-label='알림 메세지'>
<S.Alarm role='button' tabIndex={0} aria-label='알림 메세지'>
{isLoggedIn ? (
<DropDown
toggleButton={
signalData ? (
<S.BellButton onClick={() => setSignalData(null)}>
<img src={bellLogined} alt='알림' />
{signalData && <S.Dot />}
</S.BellButton>
) : (
<S.BellButton onClick={clearSignal}>
<img src={bellLogined} alt='알림' />
)
{signalData && <S.Dot />}
</S.BellButton>
}
comment={false}
>
<Notification />
</DropDown>
) : (
<img src={bell} alt='알림' />
)}
</S.Alarm> */}
</S.Alarm>
<DropDown
aria-label='프로필 드롭다운'
toggleButton={
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import useNotification from '../../../hooks/user/useNotification';

const NotificationInitializer = () => {
useNotification();

return null;
};
Comment on lines +3 to +7
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

초기화 컴포넌트 패턴이 적절합니다.

전역 SSE 연결 초기화를 위한 깔끔한 접근 방식입니다.

useNotification 훅에서 SSE 연결의 적절한 정리(cleanup)가 이루어지는지 확인해주세요. EventSource 연결이 컴포넌트 언마운트 시 제대로 닫히지 않으면 메모리 누수가 발생할 수 있습니다.


🏁 Script executed:

#!/bin/bash
# useNotification 훅에서 EventSource cleanup 확인
ast-grep --pattern $'useEffect(() => {
  $$$
  return () => {
    $$$
  }
}, $$$)'

Length of output: 3614


useNotification 훅 정의 위치와 EventSource 사용 여부를 확인하기 위해 다음 스크립트를 실행해주세요:


🏁 Script executed:

#!/bin/bash
# useNotification 훅이 정의된 파일 찾기
rg "useNotification" -n src

# EventSource 인스턴스 생성 및 cleanup 확인
rg "EventSource" -n src

Length of output: 1094


useNotification 훅의 useEffect 내부를 확인하기 위해 아래 스크립트를 실행해주세요:


🏁 Script executed:

#!/bin/bash
# useNotification.ts의 useEffect 블록 및 EventSource close 호출 여부 확인
rg "useEffect" -n src/hooks/user/useNotification.ts -A20 -B5

Length of output: 1413


useNotification 훅의 전체 cleanup 로직을 확인하기 위해 아래 스크립트를 실행해주세요:


🏁 Script executed:

#!/bin/bash
# useNotification.ts의 return cleanup 블록 확인
rg "return \\(\\) =>" -n src/hooks/user/useNotification.ts -A20 -B5

Length of output: 67


useNotification 훅의 useEffect 전체 블록(cleanup 반환 함수 포함)을 확인하기 위해 아래 스크립트를 실행해주세요:


🏁 Script executed:

#!/bin/bash
# useNotification.ts의 useEffect 블록 전체 출력 (cleanup 포함)
rg "useEffect" -n src/hooks/user/useNotification.ts -A150 -B5

Length of output: 2278


useNotification 훅에 SSE 연결 정리(cleanup) 로직 추가가 필요합니다.

현재 useEffect 내부에 EventSource를 생성만 하고, 컴포넌트 언마운트 시나 의존성 변경 시 연결을 닫는 반환 함수가 없습니다. 이로 인해 메모리 누수가 발생할 수 있습니다.

다음 부분에 cleanup 반환 함수를 추가해주세요.

  • 파일: src/hooks/user/useNotification.ts
  • 위치: useEffect(() => { … }, [queryClient, userId]); 내부 끝부분

예시 수정안:

   useEffect(() => {
     if (!userId) {
       if (eventSourceRef.current) {
         eventSourceRef.current.close();
         eventSourceRef.current = null;
       }
       return;
     }

     if (eventSourceRef.current) {
       return;
     } else {
       const eventSource = new EventSource(/* … */);
       eventSourceRef.current = eventSource;
       // 이벤트 핸들러 등록…
     }

+    // 컴포넌트 언마운트 또는 userId/queryClient 변경 시 SSE 연결 닫기
+    return () => {
+      if (eventSourceRef.current) {
+        eventSourceRef.current.close();
+        eventSourceRef.current = null;
+      }
+    };
   }, [queryClient, userId]);

위 변경으로 언마운트 시점 및 의존성 변경 시 EventSource가 정상적으로 종료됩니다.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/hooks/user/useNotification.ts around the useEffect block with
dependencies [queryClient, userId], the EventSource connection is created but
lacks a cleanup function to close it on component unmount or dependency change.
To fix this, add a return cleanup function inside the useEffect that calls
EventSource.close() to properly close the connection and prevent memory leaks.


export default NotificationInitializer;
16 changes: 16 additions & 0 deletions src/components/user/notificationLive/NotificationProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { ReactNode, useState } from 'react';
import { AlarmLive } from '../../../models/alarm';
import { SseContext } from '../../../context/SseContext';

export const NotificationProvider = ({ children }: { children: ReactNode }) => {
const [signalData, setSignalData] = useState<AlarmLive | null>(null);

const clearSignal = () => setSignalData(null);
const setSignal = (data: AlarmLive | null) => setSignalData(data);

return (
<SseContext.Provider value={{ signalData, clearSignal, setSignal }}>
{children}
</SseContext.Provider>
);
};
16 changes: 16 additions & 0 deletions src/context/SseContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { createContext, useContext } from 'react';
import { AlarmLive } from '../models/alarm';

export interface SseContextProps {
signalData: AlarmLive | null;
clearSignal: () => void;
setSignal: (data: AlarmLive | null) => void;
}

export const SseContext = createContext<SseContextProps>({
signalData: null,
clearSignal: () => {},
setSignal: () => {},
});

export const useNotificationContext = () => useContext(SseContext);
79 changes: 40 additions & 39 deletions src/hooks/user/useNotification.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import { EventSourcePolyfill, NativeEventSource } from 'event-source-polyfill';
import { useEffect, useRef, useState } from 'react';
import { useEffect, useRef } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { AlarmList } from '../queries/user/keys';
import type { AlarmLive } from '../../models/alarm';
import useAuthStore from '../../store/authStore';
import { useToast } from '../useToast';
import { useNotificationContext } from '../../context/SseContext';

const useNotification = () => {
const [signalData, setSignalData] = useState<AlarmLive | null>(null);
const queryClient = useQueryClient();
const accessToken = useAuthStore.getState().accessToken;
const userId = useAuthStore.getState().userData?.id;
const { showToast } = useToast();
const { setSignal } = useNotificationContext();

const eventSourceRef = useRef<EventSource | null>(null);
const EventSourceImpl = EventSourcePolyfill || NativeEventSource;

useEffect(() => {
if (!userId) {
Expand All @@ -27,49 +26,51 @@ const useNotification = () => {

if (eventSourceRef.current) {
return;
}
} else {
// 헤더가 아닌 파라미터 형태로 바꾸면서 Polyfill 제외 하기 -> CORS Preflight를 유발하여 요청 지연의 원인이 될 수 있음.
const eventSource = new EventSource(
`${import.meta.env.VITE_APP_API_BASE_URL}user/sse?accessToken=${
accessToken ? accessToken : ''
}`
);

// 헤더가 아닌 파라미터 형태로 바꾸면서 Polyfill 제외 하기 -> CORS Preflight를 유발하여 요청 지연의 원인이 될 수 있음.
const eventSource = new EventSourceImpl(
`${import.meta.env.VITE_APP_API_BASE_URL}user/sse`,
{
headers: {
Authorization: accessToken ? `Bearer ${accessToken}` : '',
'Content-Type': 'application/json',
},
heartbeatTimeout: 12 * 60 * 1000,
}
);
eventSourceRef.current = eventSource;

eventSource.onopen = () => {
console.log('확인');
console.log(eventSource.readyState);
};

eventSourceRef.current = eventSource;
eventSource.addEventListener('alarm', (e) => {
const event = e as MessageEvent;
try {
const eventData: AlarmLive = JSON.parse(event.data);
console.log(eventData);

eventSource.addEventListener('alarm', (e) => {
const event = e as MessageEvent;
try {
const eventData: AlarmLive = JSON.parse(event.data);
if (eventData) {
queryClient.invalidateQueries({
queryKey: [AlarmList.myAlarmList, userId],
});
}

if (eventData) {
queryClient.invalidateQueries({
queryKey: [AlarmList.myAlarmList, userId],
});
setSignal(eventData);
showToast(eventData, 3000);
} catch (error) {
console.error(error);
}
});
eventSource.onerror = (e) => {
console.error(e);
};
}

setSignalData(eventData);
} catch (error) {
console.error(error);
return () => {
if (eventSourceRef.current) {
eventSourceRef.current.close();
eventSourceRef.current = null;
}
});
eventSource.onerror = (e) => {
console.error(e);
};
}, [queryClient, userId, accessToken, EventSourceImpl]);

useEffect(() => {
if (signalData) {
showToast(signalData, 3000);
}
}, [signalData, showToast]);
return { signalData, setSignalData };
}, [queryClient, userId, accessToken]);
};

export default useNotification;
22 changes: 19 additions & 3 deletions src/routes/AppRoutes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ import {
RouterProvider,
} from 'react-router-dom';
import { lazy, Suspense } from 'react';

import LoadingSpinner from '../components/common/loadingSpinner/LoadingSpinner';
import useAuthStore from '../store/authStore';
import ProtectRoute from '../components/common/ProtectRoute';
import NotFoundPage from '../pages/notFoundPage/NotFoundPage';
import QueryErrorBoundary from '../components/common/error/QueryErrorBoundary';
import { ToastProvider } from '../components/common/Toast/ToastProvider';
import NotificationInitializer from '../components/user/notificationLive/NotificationInitializer';
import { NotificationProvider } from '../components/user/notificationLive/NotificationProvider';
import { ADMIN_ROUTE, ROUTES } from '../constants/routes';

const Login = lazy(() => import('../pages/login/Login'));
const LoginSuccess = lazy(() => import('../pages/login/LoginSuccess'));
const LoginApi = lazy(() => import('../pages/login/LoginApi'));
Expand Down Expand Up @@ -383,7 +384,22 @@ export const AppRoutes = () => {
};
});

return newRouteList;
const router = createBrowserRouter([
{
element: (
<NotificationProvider>
<ToastProvider>
<NotificationInitializer />
<Outlet />
</ToastProvider>
</NotificationProvider>
),

children: [...newRouteList, { path: '*', element: <NotFoundPage /> }],
},
]);

return <RouterProvider router={router} />;
};

export default AppRoutes;