Skip to content

Conversation

@dioo1461
Copy link
Contributor

@dioo1461 dioo1461 commented Feb 12, 2025

#️⃣ 연관된 이슈>

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

로그인 구현

  • 로그인 화면 구현
  • 로그인 기능 구현 (서버에서 쿠키를 심어 주는 방식, 클라이언트에서 따로 헤더에 추가해줄 필요 없음)

fetch util 모듈 작성

fetch를 한 단계 추상화한 request 객체를 구현했습니다.
현재는 기본적인 get, post, put, delete 메서드만 간단히 구현되어 있습니다.

  • 사용 예시
export const requestSomeData = async (): Promise<RequestSomeDataResponse> => {
  const response = await request.get('/some-api-url');
  return response;
};

export const postSomeData = async(someData: SomeData): Promise<PostSomeDataResponse> => {
  const response = await request.post('/post-some-data', someData);
  return response;
}

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

백엔드 base url은 프로젝트 루트에 .env.local 파일을 생성하고, 내부에 아래와 같은 형식으로 작성해주시면 됩니다.

/* .env.local */
VITE_API_URL=http://localhost:xxxx

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a Google login experience with an interactive modal and smooth redirection.
    • Added new navigation routes to facilitate a streamlined transition from the landing page to login.
    • Integrated React Query for improved data fetching and state management.
  • Style

    • Refined the login page design with an updated button style and backdrop for a modern look.
  • Chores

    • Enhanced routing and API request handling for improved performance and system reliability.
    • Updated ESLint configuration for better code quality practices.

@dioo1461 dioo1461 added the 🖥️ FE Frontend label Feb 12, 2025
@dioo1461 dioo1461 added this to the 3️⃣ 3차 스프린트 milestone Feb 12, 2025
@dioo1461 dioo1461 self-assigned this Feb 12, 2025
@dioo1461 dioo1461 requested a review from hamo-o as a code owner February 12, 2025 15:55
@coderabbitai
Copy link

coderabbitai bot commented Feb 12, 2025

Walkthrough

This pull request introduces several enhancements to the frontend codebase. Updates include extending the ESLint configuration with a new plugin, adding related dependencies, and refactoring an import path. A new Google login API function and its associated TypeScript interfaces are introduced to support authentication. In addition, new styling and components for the login page are added, along with lazy-loaded routes for login and OAuth redirection. Utility functions for HTTP requests and route management are also implemented, and the routing system is enhanced with React Query integration.

Changes

File(s) Change Summary
frontend/eslint.config.js
frontend/package.json
Added a new ESLint plugin import (@tanstack/eslint-plugin-query) and extended its configuration; added dependencies for @tanstack/react-query and @tanstack/eslint-plugin-query.
frontend/src/components/Input/MultiInput.tsx
frontend/src/layout/GlobalNavBar/index.tsx
frontend/src/pages/LandingPage/index.tsx
Updated the import path for intersperseElement; added a TODO comment for conditional rendering in the navbar; modified the landing page to use the useNavigate hook for the Google login button.
frontend/src/features/login/api/index.ts
frontend/src/features/login/model/index.ts
frontend/src/pages/LoginPage/index.tsx
frontend/src/pages/LoginPage/index.css.ts
Introduced the requestGoogleLoginUrl API function and new TypeScript interfaces for login responses; added the LoginPage and GoogleLoginButton components with corresponding styles; enabled the login request flow using React Query.
frontend/src/routeTree.gen.ts
frontend/src/routes/__root.tsx
frontend/src/routes/login/index.lazy.tsx
frontend/src/routes/oauth.redirect/index.lazy.tsx
Added lazy-loaded routes for login and OAuth redirection; integrated React Query and browser history subscription in the root route; updated route interfaces to include the new paths.
frontend/src/utils/fetch/index.ts
frontend/src/utils/route/index.ts
Created a new fetch utility with support for HTTP methods and error handling; added functions to manage the last visited route path using session storage.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant User
    participant LandingPage
    participant LoginPage
    participant "Google Login API" as API
    participant Browser

    User->>LandingPage: Clicks "Google Login"
    LandingPage->>LoginPage: Navigate to LoginPage route
    User->>LoginPage: Clicks "Login with Google"
    LoginPage->>API: Call requestGoogleLoginUrl()
    API-->>LoginPage: Return Google login URL
    LoginPage->>Browser: Initiate redirect using useTransition
Loading
sequenceDiagram
    autonumber
    participant User
    participant "OAuth Redirect Route" as Route
    participant "Route Utils" as Utils
    participant Browser

    User->>Route: Hit /oauth/redirect/ route
    Route->>Utils: Get last visited path
    Utils-->>Route: Return last route (or '/')
    Route->>Browser: Navigate (replace history)
Loading

Possibly related PRs

Suggested labels

🛠️ BE

Suggested reviewers

  • hamo-o

Poem

I’m a happy rabbit, coding under the moon,
Hoping through new routes that truly make code bloom.
With lazy loads and queries, the login flows so bright,
My whiskers twitch with each bug fixed right.
Leaping over errors with a joyful, fleet heart,
Celebrating these changes—a rabbit’s work of art!
🐇💻


🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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: 5

🧹 Nitpick comments (8)
frontend/src/utils/route/index.ts (2)

1-7: Add error handling for sessionStorage operations.

Consider adding error handling for cases where sessionStorage is unavailable (e.g., in private browsing mode) and path validation.

 const LAST_VISITED_PATH_KEY = 'lastVisitedPath';

 export const setLastRoutePath = (path: string) => {
+  if (!path) {
+    return;
+  }
+  try {
     sessionStorage.setItem(LAST_VISITED_PATH_KEY, path);
+  } catch (error) {
+    console.warn('Failed to save last route path:', error);
+  }
 };

7-7: Add error handling for getLastRoutePath.

Similarly, add error handling for the getter function.

-export const getLastRoutePath = () => sessionStorage.getItem(LAST_VISITED_PATH_KEY);
+export const getLastRoutePath = () => {
+  try {
+    return sessionStorage.getItem(LAST_VISITED_PATH_KEY);
+  } catch (error) {
+    console.warn('Failed to retrieve last route path:', error);
+    return null;
+  }
+};
frontend/src/pages/LoginPage/index.css.ts (1)

8-8: Fix typo in color variable name.

The color variable name contains a typo: Netural should be Neutral.

-  border: `1px solid ${vars.color.Ref.Netural[400]}`,
+  border: `1px solid ${vars.color.Ref.Neutral[400]}`,
frontend/src/routes/__root.tsx (2)

23-28: Consider improving route path management.

  1. Extract route paths as constants to avoid magic strings
  2. Add error handling for the subscription callback
+const EXCLUDED_ROUTES = ['/login', '/oauth/redirect'] as const;
+
 history.subscribe((subArgs) => {
-  const pathname = subArgs.location.pathname;
-  if (pathname !== '/login' && pathname !== '/oauth/redirect') {
-    setLastRoutePath(pathname);
-  }
+  try {
+    const pathname = subArgs.location.pathname;
+    if (!EXCLUDED_ROUTES.includes(pathname)) {
+      setLastRoutePath(pathname);
+    }
+  } catch (error) {
+    console.error('Failed to update last route path:', error);
+  }
 });

20-20: Consider configuring QueryClient options.

The default QueryClient configuration might not be optimal for your use case. Consider configuring retry attempts, cache time, etc.

-const queryClient = new QueryClient();
+const queryClient = new QueryClient({
+  defaultOptions: {
+    queries: {
+      retry: 1,
+      staleTime: 5 * 60 * 1000, // 5 minutes
+    },
+  },
+});
frontend/src/pages/LandingPage/index.tsx (1)

37-39: Add error handling to navigation.

Consider adding error handling to catch and handle navigation failures.

 const handleClickGoogleLogin = () => { 
-    navigate({ to: '/login' });
+    try {
+      navigate({ to: '/login' });
+    } catch (error) {
+      console.error('Failed to navigate to login page:', error);
+      // Consider showing a user-friendly error message
+    }
 };
frontend/src/utils/fetch/index.ts (1)

69-74: Consider adding TypeScript generics to request methods.

The request methods could benefit from TypeScript generics for better type safety of response data.

 export const request = {
-  get: (endpoint: string) => executeFetch('GET', endpoint),
-  post: (endpoint: string, body?: BodyInit) => executeFetch('POST', endpoint, body),
-  put: (endpoint: string, body?: BodyInit) => executeFetch('PUT', endpoint, body),
-  delete: (endpoint: string) => executeFetch('DELETE', endpoint),
+  get: <T = unknown>(endpoint: string) => executeFetch('GET', endpoint) as Promise<T>,
+  post: <T = unknown>(endpoint: string, body?: BodyInit) => 
+    executeFetch('POST', endpoint, body) as Promise<T>,
+  put: <T = unknown>(endpoint: string, body?: BodyInit) => 
+    executeFetch('PUT', endpoint, body) as Promise<T>,
+  delete: <T = unknown>(endpoint: string) => executeFetch('DELETE', endpoint) as Promise<T>,
 };
frontend/package.json (1)

24-24: LGTM! Consider version management strategy.

The addition of React Query and its ESLint plugin is appropriate for managing server state and API requests, which aligns well with the PR objectives. A few suggestions for version management:

  1. Consider using exact versions (5.66.0 instead of ^5.66.0) for better dependency predictability
  2. Ensure the React Query version matches across all @TanStack packages

Also applies to: 43-43

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 14bc89c and 33be036.

⛔ Files ignored due to path filters (2)
  • frontend/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • frontend/src/components/Icon/png/google-login-icon.png is excluded by !**/*.png
📒 Files selected for processing (15)
  • frontend/eslint.config.js (2 hunks)
  • frontend/package.json (2 hunks)
  • frontend/src/components/Input/MultiInput.tsx (1 hunks)
  • frontend/src/features/login/api/index.ts (1 hunks)
  • frontend/src/features/login/model/index.ts (1 hunks)
  • frontend/src/layout/GlobalNavBar/index.tsx (1 hunks)
  • frontend/src/pages/LandingPage/index.tsx (2 hunks)
  • frontend/src/pages/LoginPage/index.css.ts (1 hunks)
  • frontend/src/pages/LoginPage/index.tsx (1 hunks)
  • frontend/src/routeTree.gen.ts (9 hunks)
  • frontend/src/routes/__root.tsx (2 hunks)
  • frontend/src/routes/login/index.lazy.tsx (1 hunks)
  • frontend/src/routes/oauth.redirect/index.lazy.tsx (1 hunks)
  • frontend/src/utils/fetch/index.ts (1 hunks)
  • frontend/src/utils/route/index.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • frontend/src/layout/GlobalNavBar/index.tsx
  • frontend/src/components/Input/MultiInput.tsx
🔇 Additional comments (7)
frontend/src/features/login/model/index.ts (1)

2-8: Well-structured TypeScript interfaces!

The interfaces are clear, focused, and follow TypeScript best practices with descriptive names and appropriate types.

frontend/src/routes/login/index.lazy.tsx (1)

1-19: LGTM! Clean implementation of lazy-loaded login route.

The implementation follows best practices with:

  • Proper use of lazy loading for optimized performance
  • Clean component composition
  • Correct route configuration
frontend/src/pages/LoginPage/index.css.ts (1)

13-21: Consider documenting the z-index value.

The z-index value of 9998 is quite high. Consider:

  1. Documenting why this specific value was chosen
  2. Using a z-index variable from theme if available
  3. Verifying there are no conflicts with other overlays
❌ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Search for other high z-index values that might conflict
rg -n "z-?index.*999" --type css

Length of output: 183


Action Required: Document and Verify the High z-index Value

The backdropStyle in frontend/src/pages/LoginPage/index.css.ts uses a z-index of 9998 without any explanation. Please:

  • Document why the value 9998 was chosen.
  • Consider using a centralized z-index variable from the theme if one exists.
  • Manually verify that there are no conflicts with other overlays. (Note: The initial ripgrep command didn’t return results because it filtered by CSS file types, but since this file uses a .css.ts extension, a broader search is needed.)

To aid further investigation, you can run the following shell script to search across all file types for high z-index values:

#!/bin/bash
echo "Searching for high z-index values (9000+) across the repository:"
rg -n -e "z[-]?index\s*[:=]\s*9[0-9]{3,}" .

This will help ensure no other overlays use conflicting high z-index values.

frontend/src/pages/LoginPage/index.tsx (1)

12-21: LGTM! Good use of React Query and useTransition.

The implementation correctly handles the login flow by:

  • Using React Query for managing the login request state
  • Using useTransition to handle the redirect smoothly
  • Properly handling the success case by redirecting to the provided URL
frontend/eslint.config.js (1)

3-3: LGTM! Good addition of React Query linting.

The integration of @tanstack/eslint-plugin-query will help maintain consistent React Query usage across the codebase.

Also applies to: 13-13

frontend/src/routeTree.gen.ts (1)

26-27: Verify the lazy-loaded route configurations.

The route configurations look correct, but please verify:

  1. The existence of the lazy-loaded components at the specified paths
  2. The correct parent-child relationships in the route hierarchy

Also applies to: 43-47, 55-61

❌ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Check if the lazy-loaded components exist
fd -t f "index.lazy.tsx" "frontend/src/routes/(login|oauth.redirect)"

Length of output: 199


Below is an updated verification script that splits the search into the two expected directories and also checks the route configuration in the auto-generated file. Please execute these commands and manually verify that:

• The lazy-loaded component file (typically named index.lazy.tsx) exists in the expected directories:
  - frontend/src/routes/login
  - frontend/src/routes/oauth/redirect

• The frontend/src/routeTree.gen.ts file registers these routes correctly (i.e. includes entries for /login/ and /oauth/redirect/ with the proper hierarchy).

Run the following script:

Once these commands are executed and you confirm that the components and route configurations are correctly in place, we can conclude that the lazy-loaded route configurations are set up as expected.


🏁 Script executed:

[run_scripts]
#!/bin/bash
echo "Checking for lazy-loaded component in /login route:"
fd -t f "index.lazy.tsx" "frontend/src/routes/login"
echo "------------------------------"
echo "Checking for lazy-loaded component in /oauth/redirect route:"
fd -t f "index.lazy.tsx" "frontend/src/routes/oauth/redirect"
echo "------------------------------"
echo "Verifying routeTree entries for '/login/' in routeTree.gen.ts:"
rg "/login/" frontend/src/routeTree.gen.ts
echo "------------------------------"
echo "Verifying routeTree entries for '/oauth/redirect/' in routeTree.gen.ts:"
rg "/oauth/redirect/" frontend/src/routeTree.gen.ts

Length of output: 1862


Lazy-Loaded Routes Verification: Verify OAuth Redirect Component Path

  • The lazy-loaded component for the /login/ route exists at frontend/src/routes/login/index.lazy.tsx.
  • The auto-generated route configuration for /oauth/redirect/ exists in frontend/src/routeTree.gen.ts, but the expected lazy component was not found under frontend/src/routes/oauth/redirect/index.lazy.tsx. This indicates that either the directory/file is missing or it’s located elsewhere.

Please manually verify that the OAuth redirect lazy component exists at the expected path or update the route configuration if its location has changed.

frontend/package.json (1)

24-24: Verify the @tanstack/react-query version.

The addition of React Query is a good choice for managing server state and API requests. However, let's verify if this is the latest stable version.

✅ Verification successful

🌐 Web query:

What is the latest stable version of @tanstack/react-query?

💡 Result:

The latest stable version of @tanstack/react-query is v5.66.0, released on January 31, 2025[1]. This version includes updates across all framework implementations (React, Solid, Svelte, Vue) and associated packages like devtools and persistence utilities[1][2][6].

Key details:

  • Package updates: Affects @tanstack/react-query, @tanstack/react-query-devtools, and other framework-specific implementations[1]
  • Release frequency: Regular updates with minor/patch versions like v5.65.1 (Jan 28) and v5.64.2 (Jan 19) preceding this release[1]
  • Compatibility: Requires React v18+ and modern browsers (Chrome ≥91, Safari ≥15, etc.)[4]

For installation:

npm i @tanstack/[email protected]

The package has seen over 266k weekly downloads of its devtools companion package at time of release[6].

Citations:


@tanstack/react-query version is up-to-date.
The latest stable version is indeed v5.66.0, which matches the version specified in the package.json.

Comment on lines +5 to +8
export const requestGoogleLoginUrl = async (): Promise<RequestGoogleLoginUrlResponse> => {
const response = await request.get('/api/v1/google');
return response;
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for failed requests.

The function should handle potential API failures gracefully.

 export const requestGoogleLoginUrl = async (): Promise<RequestGoogleLoginUrlResponse> => {
+  try {
     const response = await request.get('/api/v1/google');
     return response;
+  } catch (error) {
+    console.error('Failed to request Google login URL:', error);
+    throw new Error('Failed to initialize Google login. Please try again later.');
+  }
 };
📝 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
export const requestGoogleLoginUrl = async (): Promise<RequestGoogleLoginUrlResponse> => {
const response = await request.get('/api/v1/google');
return response;
};
export const requestGoogleLoginUrl = async (): Promise<RequestGoogleLoginUrlResponse> => {
try {
const response = await request.get('/api/v1/google');
return response;
} catch (error) {
console.error('Failed to request Google login URL:', error);
throw new Error('Failed to initialize Google login. Please try again later.');
}
};

Comment on lines 5 to 14
const Redirect = () => {
const navigate = useNavigate();
const lastPath = getLastRoutePath();
navigate({
to: lastPath || '/',
replace: true,
});

return <div></div>;
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add loading state and error handling.

The component should handle loading and error states gracefully, and provide visual feedback to users.

 const Redirect = () => {
   const navigate = useNavigate();
   const lastPath = getLastRoutePath();
+  const [error, setError] = useState<string | null>(null);
+
+  useEffect(() => {
+    try {
       navigate({
         to: lastPath || '/',
         replace: true,
+      }).catch(err => {
+        console.error('Navigation failed:', err);
+        setError('Failed to redirect. Please try again.');
       });
+    } catch (err) {
+      console.error('Navigation failed:', err);
+      setError('Failed to redirect. Please try again.');
+    }
+  }, [navigate, lastPath]);
+
+  if (error) {
+    return <div className="error-message">{error}</div>;
+  }

-  return <div></div>;
+  return <div className="loading-spinner">Redirecting...</div>;
 };
📝 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 Redirect = () => {
const navigate = useNavigate();
const lastPath = getLastRoutePath();
navigate({
to: lastPath || '/',
replace: true,
});
return <div></div>;
};
const Redirect = () => {
const navigate = useNavigate();
const lastPath = getLastRoutePath();
const [error, setError] = useState<string | null>(null);
useEffect(() => {
try {
navigate({
to: lastPath || '/',
replace: true,
}).catch(err => {
console.error('Navigation failed:', err);
setError('Failed to redirect. Please try again.');
});
} catch (err) {
console.error('Navigation failed:', err);
setError('Failed to redirect. Please try again.');
}
}, [navigate, lastPath]);
if (error) {
return <div className="error-message">{error}</div>;
}
return <div className="loading-spinner">Redirecting...</div>;
};

Comment on lines +28 to +52
export const executeFetch = async (
method: Method,
endpoint: string,
body?: BodyInit,
options?: RequestOptions,
) => {
const fetchOptions = buildFetchOptions(options);

try {
const response = await fetch(BASE_URL + endpoint, {
method: method,
body: JSON.stringify(body),
...fetchOptions,
});

if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}

const data = await response.json();
return data;
} catch (error) {
throw new Error(`Network Error : ${error}`);
}
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling in executeFetch.

The current error handling could be improved by:

  1. Parsing error responses for better error messages
  2. Adding retry logic for network errors
  3. Handling non-JSON responses
 export const executeFetch = async (
   method: Method,
   endpoint: string,
   body?: BodyInit,
   options?: RequestOptions,
 ) => {
   const fetchOptions = buildFetchOptions(options);

   try {
     const response = await fetch(BASE_URL + endpoint, {
       method: method,
       body: JSON.stringify(body),
       ...fetchOptions,
     });

     if (!response.ok) {
-      throw new Error(`HTTP Error: ${response.status}`);
+      const errorData = await response.json().catch(() => null);
+      throw new Error(
+        `HTTP Error ${response.status}: ${
+          errorData?.message || response.statusText
+        }`
+      );
     }

+    const contentType = response.headers.get('content-type');
+    if (contentType?.includes('application/json')) {
       const data = await response.json();
       return data;
+    }
+    return response.text();
   } catch (error) {
-    throw new Error(`Network Error : ${error}`);
+    if (error instanceof Error) {
+      throw error;
+    }
+    throw new Error(`Network Error: ${String(error)}`);
   }
 };
📝 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
export const executeFetch = async (
method: Method,
endpoint: string,
body?: BodyInit,
options?: RequestOptions,
) => {
const fetchOptions = buildFetchOptions(options);
try {
const response = await fetch(BASE_URL + endpoint, {
method: method,
body: JSON.stringify(body),
...fetchOptions,
});
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
throw new Error(`Network Error : ${error}`);
}
};
export const executeFetch = async (
method: Method,
endpoint: string,
body?: BodyInit,
options?: RequestOptions,
) => {
const fetchOptions = buildFetchOptions(options);
try {
const response = await fetch(BASE_URL + endpoint, {
method: method,
body: JSON.stringify(body),
...fetchOptions,
});
if (!response.ok) {
const errorData = await response.json().catch(() => null);
throw new Error(
`HTTP Error ${response.status}: ${
errorData?.message || response.statusText
}`
);
}
const contentType = response.headers.get('content-type');
if (contentType?.includes('application/json')) {
const data = await response.json();
return data;
}
return response.text();
} catch (error) {
if (error instanceof Error) {
throw error;
}
throw new Error(`Network Error: ${String(error)}`);
}
};

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: 1

🧹 Nitpick comments (1)
frontend/src/pages/LoginPage/index.tsx (1)

45-64: Enhance button accessibility.

The button could benefit from improved accessibility features.

Add ARIA attributes and loading state indicator:

 const GoogleLoginButton = ({ onClick, disabled }: { onClick: () => void; disabled: boolean }) => (
   <Flex
     align='center'
     as='button'
+    aria-label="Google로 시작하기"
+    aria-busy={disabled}
     className={googleLoginButtonStyle}
     disabled={disabled}
     gap={200}
     justify='center'
     onClick={onClick}
     width='full'
   >
     <img
       alt='Google 로그인 아이콘'
       height='20px'
       src={googleLoginIcon}
       width='20px'
     />
-    <Text color={vars.color.Ref.Netural[400]} typo='t3'>Google로 시작하기</Text>
+    <Text color={vars.color.Ref.Netural[400]} typo='t3'>
+      {disabled ? '로그인 중...' : 'Google로 시작하기'}
+    </Text>
   </Flex>
 );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 33be036 and f49f090.

📒 Files selected for processing (2)
  • frontend/package.json (2 hunks)
  • frontend/src/pages/LoginPage/index.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/package.json
🔇 Additional comments (2)
frontend/src/pages/LoginPage/index.tsx (2)

1-11: LGTM! Well-organized imports.

The imports are properly organized and the Google login icon is correctly imported as a module.


33-33: Consider making the modal's open state dynamic.

The modal is always open (isOpen={true}). Consider managing its state if there are cases where it should be hidden.

Could you clarify if there are any scenarios where the modal should be hidden? If not, we could remove the isOpen prop entirely since it's always true.

Comment on lines 15 to 22
const googleLogin = useMutation({
mutationFn: requestGoogleLoginUrl,
onSuccess: ({ url }) => {
startRedirectTransition(async () => {
window.location.href = url;
});
},
});
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 for failed login attempts.

The mutation doesn't handle API failures. Users won't receive feedback if the login request fails.

Add error handling:

 const googleLogin = useMutation({
   mutationFn: requestGoogleLoginUrl,
   onSuccess: ({ url }) => {
     startRedirectTransition(async () => {
       window.location.href = url;
     });
   },
+  onError: (error) => {
+    // Handle error (e.g., show error message to user)
+    console.error('Login failed:', error);
+  },
 });
📝 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 googleLogin = useMutation({
mutationFn: requestGoogleLoginUrl,
onSuccess: ({ url }) => {
startRedirectTransition(async () => {
window.location.href = url;
});
},
});
const googleLogin = useMutation({
mutationFn: requestGoogleLoginUrl,
onSuccess: ({ url }) => {
startRedirectTransition(async () => {
window.location.href = url;
});
},
onError: (error) => {
// Handle error (e.g., show error message to user)
console.error('Login failed:', error);
},
});

Redirect 라우트 내에서, useEffect 밖에서 navigate를 하고 있었기 때문에 발생한 문제였음. 컴포넌트가 렌더링 완료되기 전 상태가 업데이트되면, 그로 인해 무한 루프가 발생할 수 있기 때문에 상태 업데이트는 항상 렌더링이 완료된 시점에 수행해야 함
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: 1

♻️ Duplicate comments (1)
frontend/src/pages/LoginPage/index.tsx (1)

13-18: ⚠️ Potential issue

Add loading and error handling to the mutation.

The mutation lacks loading state indication and error handling, which affects user experience.

Apply this diff:

 const googleLogin = useMutation({
   mutationFn: requestGoogleLoginUrl,
   onSuccess: ({ url }) => {
     window.location.href = url;
   },
+  onError: (error) => {
+    console.error('Login failed:', error);
+    // Add error notification/toast here
+  },
 });
🧹 Nitpick comments (2)
frontend/src/pages/LoginPage/index.tsx (2)

29-29: Make Modal's isOpen state dynamic.

The Modal is always open (isOpen={true}). Consider managing this with state for better control.

Apply this diff:

+import { useState } from 'react';
+
 const LoginPage = () => {
+  const [isModalOpen, setIsModalOpen] = useState(true);
+
   return (
     <div className={backdropStyle}>
       <Modal
         description={...}
-        isOpen={true}
+        isOpen={isModalOpen}
+        onClose={() => setIsModalOpen(false)}
         ...
       >

41-59: Enhance button accessibility.

The button could benefit from additional accessibility attributes.

Apply this diff:

 const GoogleLoginButton = ({ onClick }: { onClick: () => void }) => (
   <Flex
     align='center'
     as='button'
+    aria-label='Google로 로그인'
+    role='button'
+    tabIndex={0}
+    onKeyPress={(e) => e.key === 'Enter' && onClick()}
     className={googleLoginButtonStyle}
     gap={200}
     justify='center'
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f49f090 and 4557124.

📒 Files selected for processing (2)
  • frontend/src/pages/LoginPage/index.tsx (1 hunks)
  • frontend/src/routes/oauth.redirect/index.lazy.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/routes/oauth.redirect/index.lazy.tsx

Comment on lines +15 to +17
onSuccess: ({ url }) => {
window.location.href = url;
},
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use React Router's navigation instead of direct window.location modification.

Direct window.location modification breaks the browser's history stack. Consider using React Router's navigation methods.

Apply this diff:

+import { useNavigate } from 'react-router-dom';
+
 const LoginPage = () => {
+  const navigate = useNavigate();
   const googleLogin = useMutation({
     mutationFn: requestGoogleLoginUrl,
     onSuccess: ({ url }) => {
-      window.location.href = url;
+      navigate(url);
     },
   });
📝 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
onSuccess: ({ url }) => {
window.location.href = url;
},
import React from 'react';
import { useMutation } from 'react-query';
import { useNavigate } from 'react-router-dom';
const LoginPage = () => {
const navigate = useNavigate();
const googleLogin = useMutation({
mutationFn: requestGoogleLoginUrl,
onSuccess: ({ url }) => {
navigate(url);
},
});
// ...rest of the LoginPage component code
return (
// JSX code for LoginPage
);
};
export default LoginPage;

Copy link
Contributor

@hamo-o hamo-o left a comment

Choose a reason for hiding this comment

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

굿굿 수고하셨어요! 같이 문제점들 고쳐서 어프룹합니당

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