-
Notifications
You must be signed in to change notification settings - Fork 3
Fix: beforeErrorHook에 전역 상태 초기화 및 TanStack Query 캐시 무효화 로직 추가 #547
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Walkthrough401 상태 코드와 보호된 페이지 여부를 확인하는 조건문이 단순화되었습니다. 이제 Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
Poem
Note 🔌 MCP (Model Context Protocol) integration is now available in Early Access!Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Preview Deployment Ready!🔗 Preview URL: https://roam-ready-l8630wllg-yongmins-projects-bf5f7733.vercel.app This preview will be automatically updated on new commits. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
src/shared/libs/formatErrorResponseHooks.ts (1)
26-36: 리다이렉트 직후 불필요한 로직 실행을 방지하기 위해return을 추가하세요
window.location.href를 설정한 뒤에도 함수는 계속 실행됩니다(비동기 환경에서는 즉시 탐색이 보장되지 않음). 안전하게 종료하려면 리다이렉트 이후에return으로 조기 종료해 주는 편이 좋습니다.window.location.href = redirectUrl.toString(); + return error; // 리다이렉트 후 추가 로직 방지
🧹 Nitpick comments (2)
src/shared/libs/formatErrorResponseHooks.ts (2)
12-13:protectedPageRoutes는 함수 외부로 이동하여 재할당을 방지하세요
protectedPageRoutes는 불변 상수이므로,beforeErrorHook가 호출될 때마다 새 배열을 생성할 필요가 없습니다. 파일 상단(모듈 스코프)으로 옮기면 미세하지만 불필요한 메모리 할당을 줄일 수 있고 의도도 더 명확해집니다.
19-20:invalidateQueries반환 Promise를await로 명시적으로 처리하세요
queryClient.invalidateQueries는 Promise를 반환합니다. 뒤이어 즉시 리다이렉트가 발생할 수 있으므로, 캐시 무효화가 완료되기 전에 네트워크 이동이 일어나면 의도한 효과가 적용되지 않을 수 있습니다.- queryClient.invalidateQueries({ queryKey: ['user', 'me'] }); // 캐시 무효화 + await queryClient.invalidateQueries({ queryKey: ['user', 'me'] }); // 캐시 무효화
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/shared/libs/formatErrorResponseHooks.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/shared/libs/formatErrorResponseHooks.ts (1)
src/shared/libs/queryClient.ts (1)
queryClient(14-24)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: vercel-preview
536bc1b to
82c53a2
Compare
✅ Preview Deployment Ready!🔗 Preview URL: https://roam-ready-otbx3bfjd-yongmins-projects-bf5f7733.vercel.app This preview will be automatically updated on new commits. |
82c53a2 to
e205e4c
Compare
✅ Preview Deployment Ready!🔗 Preview URL: https://roam-ready-f6r0vgmmz-yongmins-projects-bf5f7733.vercel.app This preview will be automatically updated on new commits. |
5461670 to
5449e7b
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/domain/Auth/hooks/useUser.ts (2)
60-61: 네트워크 요청 빈도 증가에 대한 검토가 필요합니다.
refetchOnWindowFocus와refetchOnReconnect를 모두true로 설정하면 사용자가 창을 전환하거나 네트워크가 재연결될 때마다 API 요청이 발생합니다. 이는 불필요한 네트워크 트래픽을 증가시킬 수 있습니다.사용자 경험과 서버 부하를 고려하여 다음 중 하나를 검토해보세요:
staleTime을 적절한 값(예: 1분)으로 설정하여 불필요한 요청 방지- 또는
refetchOnWindowFocus만 활성화하고refetchOnReconnect는 제거const queryResult = useQuery({ queryKey: ['user', 'me'], queryFn: getMe, retry: 1, + staleTime: 1000 * 60, // 1분간 fresh 상태 유지 refetchOnWindowFocus: true, - refetchOnReconnect: true, });
29-29: 문서가 실제 구현과 일치하지 않습니다.29번 줄의 JSDoc에서
staleTime이 5분으로 설정된다고 명시되어 있지만, 실제 코드에서는staleTime이 제거되었습니다.- * @property {number} staleTime - 데이터를 'fresh' 상태로 유지하는 시간 (5분). + * @property {boolean} refetchOnWindowFocus - 윈도우 포커스 시 데이터를 자동으로 다시 가져올지 여부. + * @property {boolean} refetchOnReconnect - 네트워크 재연결 시 데이터를 자동으로 다시 가져올지 여부.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/app/_components/AuthInitializer.tsx(2 hunks)src/domain/Auth/hooks/useUser.ts(1 hunks)src/middleware.ts(2 hunks)src/shared/libs/apiClient.ts(1 hunks)src/shared/libs/formatErrorResponseHooks.ts(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- src/shared/libs/formatErrorResponseHooks.ts
- src/shared/libs/apiClient.ts
- src/middleware.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/app/_components/AuthInitializer.tsx (1)
src/domain/Auth/hooks/useUser.ts (1)
useUser(52-81)
| */ | ||
| export default function AuthInitializer() { | ||
| useUser(); | ||
| const { refetch } = useUser(); // 쿼리 객체를 받아서 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
초기화 로직이 명확해졌습니다.
refetch를 명시적으로 호출하여 앱 로드 시 사용자 데이터를 강제로 가져오는 로직이 명확해졌습니다. 이는 인증 상태 동기화를 보장하는 좋은 접근 방식입니다.
다만 useQuery는 기본적으로 컴포넌트 마운트 시에도 실행되므로, refetch() 호출이 중복 요청을 발생시킬 가능성이 있습니다.
중복 요청 여부를 확인하기 위해 다음 스크립트를 실행하여 useQuery의 기본 설정을 확인해보세요:
Also applies to: 17-20
🏁 Script executed:
#!/bin/bash
# useQuery 기본 동작 확인을 위해 관련 설정들을 찾아봅니다
rg -A 10 -B 5 "useQuery|QueryClient" --type ts --type tsxLength of output: 87
tsx 파일 타입 필터가 인식되지 않아, 전체 파일을 대상으로 useQuery와 QueryClient를 다시 검색해주세요.
🏁 Script executed:
#!/bin/bash
# 전체 파일에서 useQuery 및 QueryClient 사용 위치를 확인합니다
rg -n -A5 -B5 "useQuery|QueryClient" .Length of output: 33839
중복 네트워크 요청 방지 검토 필요
AuthInitializer.tsx에서 useUser 훅을 통해 { refetch }를 분해한 뒤, useEffect로 마운트 시 다시 refetch()를 호출하고 있습니다.
그러나 useUser 내부에는 다음과 같이 useQuery를 사용하고 있어:
- 컴포넌트 마운트 시 기본적으로
getMe요청을 자동 실행 staleTime기본값(0)으로 마운트마다 재요청이 보장됨
따라서 useEffect에서 추가로 호출하는 refetch()는 불필요한 중복 요청을 유발할 수 있습니다.
수정 제안:
useEffect내의refetch()호출 제거- 또는
staleTime/refetchOnMount옵션을 조정해 의도한 동작만 발생하도록 변경
교정이 필요한 위치:
- src/app/_components/AuthInitializer.tsx
- 15번 줄:
const { refetch } = useUser(); - 17–20번 줄:
useEffect(() => { refetch() }, [refetch])
- 15번 줄:
🤖 Prompt for AI Agents
In src/app/_components/AuthInitializer.tsx around lines 15 to 20, the useEffect
hook calls refetch() on mount, causing redundant network requests because
useUser's underlying useQuery already fetches data on mount with staleTime 0. To
fix this, remove the useEffect block that calls refetch(), or alternatively
adjust the useUser hook's useQuery options by setting staleTime to a higher
value or refetchOnMount to false to prevent duplicate requests.
5449e7b to
e65e596
Compare
e65e596 to
65b1faa
Compare
✅ Preview Deployment Ready!🔗 Preview URL: https://roam-ready-2woqm5ocj-yongmins-projects-bf5f7733.vercel.app This preview will be automatically updated on new commits. |
👻 관련 이슈 번호
👻 요약
사용자 인증 관련 로직을 개선하여 불필요한 네트워크 요청을 줄이고, 401 에러(인증 실패) 처리 과정을 효율적으로 개선
👻 주요 변경 사항
API 클라이언트의 beforeErrorHook에 401 에러를 처리하는 로직을 추가했습니다.
src/domain/Auth/hooks/useUser.ts 수정
maxAge 옵션의 테스트용 주석을 정리하고, 최종 maxAge가 60 * 60으로 설정되도록 변경했습니다.
kakao Oauth gif 추가
👻 체크리스트
📷 UI 변경 사항
👻 문제 사항
👻 논의 사항
👻 기타 참고 사항
Summary by CodeRabbit