Skip to content

Conversation

@hamo-o
Copy link
Contributor

@hamo-o hamo-o commented Jun 25, 2025

#️⃣ 연관된 이슈>

📝 작업 내용> 이번 PR에서 작업한 내용을 간략히 설명해주세요(이미지 첨부 가능)

StrictMode에서 로그인 요청이 중복으로 나가는 문제를 해결했습니다.
해결과정: https://hamo0.tistory.com/100

🙏 여기는 꼭 봐주세요! > 리뷰어가 특별히 봐주었으면 하는 부분이 있다면 작성해주세요

컴포넌트 외부에서 사용할 수 있는 뮤테이션 유틸을 만들었는데 조금 복잡한 것 같아 이부분 위주로 봐주시면 좋을 것 같습니다.

Summary by CodeRabbit

  • Refactor

    • Improved OAuth redirect routes by moving logic from React components to route-level lifecycle methods for better performance and maintainability.
    • Updated JWT login mutation to use a new mutation utility and redirect handling, changing the mutation hook’s usage and naming.
  • New Features

    • Introduced a utility for creating and managing mutations outside React components, with global error handling and support for redirect errors.
  • Chores

    • Updated .gitignore to exclude all .env files in the frontend.
    • Enhanced utility exports for easier access to new mutation helpers.
  • Style

    • No user-facing style changes included.

@hamo-o hamo-o requested a review from dioo1461 as a code owner June 25, 2025 11:26
@hamo-o hamo-o added the 🖥️ FE Frontend label Jun 25, 2025
@coderabbitai
Copy link

coderabbitai bot commented Jun 25, 2025

Walkthrough

This update introduces a new mutation utility for handling asynchronous operations outside React components and refactors OAuth redirect routes and login mutation logic to use route-level lifecycle hooks and the new mutation utility. Additional exports are added for utility modules, and the .gitignore is updated to ignore environment files.

Changes

File(s) Change Summary
frontend/.gitignore Added .env* pattern to ignore all environment files.
frontend/apps/client/src/features/login/api/mutations.ts Refactored login mutation: replaced useMutation with createMutation, switched to redirect throws, renamed hook and return value.
frontend/apps/client/src/main.tsx Set global mutation error handler using setDefaultMutationErrorHandler.
frontend/apps/client/src/routes/oauth.redirect/calendar/index.tsx Moved query invalidation and redirect logic from component to route's beforeLoad hook.
frontend/apps/client/src/routes/oauth.redirect/login/index.tsx Moved login mutation from component to route's beforeLoad hook, using new mutation utility.
frontend/packages/core/src/utils/index.ts Re-exported all exports from ./network.
frontend/packages/core/src/utils/network/createMutation.ts Introduced new mutation utility for async operations and error handling outside React.
frontend/packages/core/src/utils/network/index.ts Re-exported all exports from ./createMutation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Router
    participant RouteBeforeLoad
    participant MutationUtil
    participant QueryClient

    User->>Router: Navigates to /oauth.redirect/login?code=...
    Router->>RouteBeforeLoad: Calls beforeLoad with params
    RouteBeforeLoad->>MutationUtil: Calls jwtMutation().mutateAsync(code)
    MutationUtil->>MutationUtil: Performs login mutation
    alt Success
        MutationUtil->>RouteBeforeLoad: Throws redirect to lastPath or /home
    else Error
        MutationUtil->>RouteBeforeLoad: Throws redirect to /login
    end
    RouteBeforeLoad->>Router: Handles redirect
Loading
sequenceDiagram
    participant User
    participant Router
    participant RouteBeforeLoad
    participant QueryClient

    User->>Router: Navigates to /oauth.redirect/calendar
    Router->>RouteBeforeLoad: Calls beforeLoad
    RouteBeforeLoad->>QueryClient: Invalidate calendar queries
    RouteBeforeLoad->>Router: Throws redirect to /my-calendar
Loading

Possibly related PRs

  • #181: Introduced the original useJWTMutation hook and login mutation logic, which is directly refactored in this PR.
  • #89: Established the Tanstack Router setup and routing conventions, which are built upon by the route-level refactors in this PR.

Poem

A hop, a skip, a redirect anew,
With mutations now handled outside the view.
BeforeLoad leaps in, no more hooks to chase,
Errors corralled in a single place.
Environment secrets hidden from sight—
The code hops forward, feeling light! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
frontend/packages/core/src/utils/network/createMutation.ts (2)

44-51: Consider consistent error handling between mutate and mutateAsync.

The mutate method has inconsistent error handling compared to mutateAsync:

  1. Missing redirect error check: mutate doesn't check for redirect errors before calling the global handler
  2. No error rethrowing: Non-redirect errors are swallowed in mutate, which might hide important errors
const mutate = (args: TArgs) => {
  options.mutationFn(args)
    .then(res => options.onSuccess?.(res, args))
    .catch(err => {
+     if (isRedirectError(err)) {
+       // For redirect errors, we might want to handle them differently
+       // or at least not call the global error handler
+       options.onError?.(err, args);
+       return;
+     }
      globalHandleError?.(err);
      options.onError?.(err, args);
    });
};

Consider whether mutate should handle redirect errors differently since it's fire-and-forget.


25-27: Add JSDoc documentation for the complex utility function.

Given the complexity noted in the Korean comment, consider adding comprehensive JSDoc documentation to help other developers understand the utility:

/**
- * 리액트 컴포넌트 외부에서 사용할 수 있는 뮤테이션 함수 생성기.
+ * Creates mutation functions that can be used outside React components.
+ * 
+ * @template TArgs - The type of arguments passed to the mutation function
+ * @template TRes - The type of response returned by the mutation function
+ * 
+ * @param options - Configuration object for the mutation
+ * @param options.mutationFn - The async function to execute
+ * @param options.onSuccess - Callback executed on successful mutation
+ * @param options.onError - Callback executed on mutation error
+ * 
+ * @returns Object with mutate (fire-and-forget) and mutateAsync (awaitable) methods
+ * 
+ * @example
+ * ```ts
+ * const { mutateAsync } = createMutation({
+ *   mutationFn: async (data) => api.post('/endpoint', data),
+ *   onSuccess: (response, args) => {
+ *     throw redirect({ to: '/success' });
+ *   },
+ *   onError: () => {
+ *     throw redirect({ to: '/error' });
+ *   }
+ * });
+ * ```
 */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac77e68 and 91e989f.

📒 Files selected for processing (8)
  • frontend/.gitignore (1 hunks)
  • frontend/apps/client/src/features/login/api/mutations.ts (2 hunks)
  • frontend/apps/client/src/main.tsx (2 hunks)
  • frontend/apps/client/src/routes/oauth.redirect/calendar/index.tsx (1 hunks)
  • frontend/apps/client/src/routes/oauth.redirect/login/index.tsx (1 hunks)
  • frontend/packages/core/src/utils/index.ts (1 hunks)
  • frontend/packages/core/src/utils/network/createMutation.ts (1 hunks)
  • frontend/packages/core/src/utils/network/index.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: frontend
🔇 Additional comments (7)
frontend/.gitignore (1)

14-14: LGTM! Essential security practice.

Adding .env* to .gitignore is crucial for preventing accidental commits of environment files that may contain sensitive configuration data, especially relevant for OAuth authentication flows.

frontend/apps/client/src/main.tsx (2)

1-1: LGTM! Consistent error handling setup.

Importing setDefaultMutationErrorHandler establishes global mutation error handling that complements the existing query error handling infrastructure.


45-45: LGTM! Proper global error handler configuration.

Using the same handleError function for mutations that's already used for queries ensures consistent error handling across all async operations.

frontend/packages/core/src/utils/index.ts (1)

6-6: LGTM! Consistent module export pattern.

The addition follows the established pattern of re-exporting utility modules, making the new network utilities properly accessible.

frontend/packages/core/src/utils/network/index.ts (1)

1-1: LGTM! Clean module organization.

Simple and standard index file pattern for re-exporting the createMutation utilities.

frontend/apps/client/src/routes/oauth.redirect/calendar/index.tsx (1)

6-9: LGTM! Excellent refactoring to avoid React StrictMode issues.

Moving the query invalidation and redirect logic from React component lifecycle to route beforeLoad is the correct approach to prevent duplicate executions under React StrictMode. The implementation properly:

  • Uses async/await for the lifecycle method
  • Accesses queryClient from route context
  • Invalidates queries before redirecting
  • Uses the throw redirect pattern correctly
frontend/apps/client/src/features/login/api/mutations.ts (1)

12-29: LGTM! Well-implemented mutation refactor with proper redirect handling.

The refactor from React Query to the custom createMutation utility is well-executed:

  1. Proper redirect pattern: Using throw redirect() instead of imperative navigation aligns with the route-level lifecycle approach.
  2. Consistent error handling: Both success and error paths use redirects, ensuring predictable navigation flow.
  3. Clean API: Returning { loginMutate: mutateAsync } provides a clear interface for async usage in beforeLoad.

The mutation will properly handle authentication flow by redirecting to the intended destination on success or back to login on failure.

Comment on lines +11 to +17
beforeLoad: async ({ search }: { search: SearchWithCode }) => {
const lastPath = getLastRoutePath();
const { loginMutate } = jwtMutation();
if (search.code) {
await loginMutate({ code: search.code, lastPath });
}
},
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling and validation for the beforeLoad lifecycle.

The beforeLoad function lacks proper error handling and validation:

  1. Missing code validation: The function should validate that search.code exists and is a valid string before proceeding with the mutation.
  2. Unhandled mutation errors: If loginMutate throws an error that isn't a redirect, it will cause the route loading to fail without proper user feedback.
  3. Type safety concern: The SearchWithCode type allows code to be undefined, but the logic assumes it exists.
export const Route = createFileRoute('/oauth/redirect/login/')({
- beforeLoad: async ({ search }: { search: SearchWithCode }) => {
+ beforeLoad: async ({ search }: { search: SearchWithCode }) => {
+   if (!search.code) {
+     throw redirect({ to: '/login' });
+   }
+   
    const lastPath = getLastRoutePath();
    const { loginMutate } = jwtMutation();
-   if (search.code) {
-     await loginMutate({ code: search.code, lastPath });
-   }
+   
+   try {
+     await loginMutate({ code: search.code, lastPath });
+   } catch (error) {
+     // Let redirect errors bubble up, handle others
+     if (error && typeof error === 'object' && 'isRedirect' in error) {
+       throw error;
+     }
+     throw redirect({ to: '/login' });
+   }
  },
});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
beforeLoad: async ({ search }: { search: SearchWithCode }) => {
const lastPath = getLastRoutePath();
const { loginMutate } = jwtMutation();
if (search.code) {
await loginMutate({ code: search.code, lastPath });
}
},
export const Route = createFileRoute('/oauth/redirect/login/')({
beforeLoad: async ({ search }: { search: SearchWithCode }) => {
// Validate that we actually have a code, otherwise redirect to login
if (!search.code) {
throw redirect({ to: '/login' });
}
const lastPath = getLastRoutePath();
const { loginMutate } = jwtMutation();
try {
await loginMutate({ code: search.code, lastPath });
} catch (error) {
// If it’s a redirect-error, let it bubble up; otherwise go back to login
if (error && typeof error === 'object' && 'isRedirect' in error) {
throw error;
}
throw redirect({ to: '/login' });
}
},
});
🤖 Prompt for AI Agents
In frontend/apps/client/src/routes/oauth.redirect/login/index.tsx around lines
11 to 17, the beforeLoad function needs improved error handling and validation.
First, add a check to ensure search.code is a defined, valid string before
calling loginMutate. Then, wrap the loginMutate call in a try-catch block to
handle any errors; if the error is not a redirect, catch it and provide
appropriate user feedback or logging to prevent route loading failure. Also,
adjust the type handling to safely account for the possibility that search.code
may be undefined.

Comment on lines +16 to +19
const isRedirectError = (error: unknown): boolean => (
typeof error === 'object' && error !== null
&& 'isRedirect' in error && error.isRedirect === true
);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type safety of the redirect error detection.

The isRedirectError function uses loose type checking that could lead to false positives:

-const isRedirectError = (error: unknown): boolean => (
-  typeof error === 'object' && error !== null 
-    && 'isRedirect' in error && error.isRedirect === true
-);
+const isRedirectError = (error: unknown): error is { isRedirect: true } => (
+  typeof error === 'object' && 
+  error !== null && 
+  'isRedirect' in error && 
+  (error as { isRedirect: unknown }).isRedirect === true
+);

This provides:

  1. Type guard return type: The function now acts as a proper type guard
  2. Safer property access: Explicitly casts to access the isRedirect property
  3. Better type inference: TypeScript will know the error type after the guard
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const isRedirectError = (error: unknown): boolean => (
typeof error === 'object' && error !== null
&& 'isRedirect' in error && error.isRedirect === true
);
const isRedirectError = (error: unknown): error is { isRedirect: true } => (
typeof error === 'object' &&
error !== null &&
'isRedirect' in error &&
(error as { isRedirect: unknown }).isRedirect === true
);
🤖 Prompt for AI Agents
In frontend/packages/core/src/utils/network/createMutation.ts around lines 16 to
19, the isRedirectError function uses loose type checking that may cause false
positives. Refactor the function to be a proper TypeScript type guard by
specifying its return type accordingly, explicitly cast the error to a type that
includes the isRedirect property before accessing it, and ensure the function
narrows the error type for better type inference and safer property access.

mutateAsync: (args: TArgs) => Promise<void>;
};

let globalHandleError: (error: unknown) => unknown;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Initialize the global error handler to prevent runtime errors.

The global error handler is declared but not initialized, which could cause issues if createMutation is used before setDefaultMutationErrorHandler is called:

-let globalHandleError: (error: unknown) => unknown;
+let globalHandleError: (error: unknown) => unknown = () => {
+  // Default no-op handler to prevent runtime errors
+};

Or alternatively, add proper null checking:

-      globalHandleError?.(error);
+      if (globalHandleError) {
+        globalHandleError(error);
+      }

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

🤖 Prompt for AI Agents
In frontend/packages/core/src/utils/network/createMutation.ts at line 14, the
global error handler variable is declared but not initialized, which can cause
runtime errors if used before being set. Initialize globalHandleError with a
default no-op function or a function that safely handles errors to prevent
undefined behavior. Alternatively, add null or undefined checks before invoking
globalHandleError to ensure safe usage.

Copy link
Contributor

@dioo1461 dioo1461 left a comment

Choose a reason for hiding this comment

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

잘 동작하는 것 확인했어요! 고생하셨습니다!!

.then(res => options.onSuccess?.(res, args))
.catch(err => {
globalHandleError?.(err);
options.onError?.(err, args);
Copy link
Contributor

Choose a reason for hiding this comment

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

just ask;
이 부분에서는 에러를 던져주지 않아도 괜찮을까요? (궁금해서 여쭤봅니다)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🖥️ FE Frontend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants