Skip to content

[feat] 관리자 책 이야기 및 댓글 삭제 api 연결 - #216

Merged
yhi9839 merged 2 commits into
devfrom
feat/210-admin-api
Mar 20, 2026
Merged

yhi9839 merged 2 commits into
devfrom
feat/210-admin-api

Conversation

@nonoididnt

@nonoididnt nonoididnt commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

📌 개요 (Summary)

관리자용 책 이야기 삭제, 댓글 삭제 API 연결

🛠️ 변경 사항 (Changes)

  • 새로운 기능 추가
  • 버그 수정
  • 코드 리팩토링
  • 문서 업데이트
  • 기타 (설명: )

📸 스크린샷 (Screenshots)

(UI 변경 사항이 있다면 첨부해주세요)

✅ 체크리스트 (Checklist)

  • 빌드가 성공적으로 수행되었나요? (pnpm build)
  • 린트 에러가 없나요? (pnpm lint)
  • 불필요한 콘솔 로그나 주석을 제거했나요?

Summary by CodeRabbit

Release Notes

  • New Features
    • Enabled comment management in admin story details with support for nested replies and comments
    • Added ability to delete stories and comments with confirmation dialogs
    • Introduced comment reporting functionality for content moderation

@nonoididnt nonoididnt linked an issue Mar 20, 2026 that may be closed by this pull request
1 of 4 tasks
@vercel

vercel Bot commented Mar 20, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
check-mo Ready Ready Preview, Comment Mar 20, 2026 5:36am
checkmo Ready Ready Preview, Comment Mar 20, 2026 5:36am

@coderabbitai

coderabbitai Bot commented Mar 20, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2eb6df09-fa4c-463e-89e5-010d7e693994

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR introduces a new CommentSection component for admin story details with nested comment management, adds delete functionality for stories and comments via new API endpoints and handlers, and updates the admin story detail page to use the new comment component with an explicit id prop.

Changes

Cohort / File(s) Summary
Admin Story Detail Page
src/app/(admin)/admin/(app)/stories/[id]/page.tsx
Updated import path for CommentSection from comment module to admin-specific module; added explicit id prop to BookstoryDetail component.
Story Detail Component
src/components/base-ui/Admin/stories/bookstory_detail.tsx
Added handleDelete async action with confirmation dialog and navigation to story list; rewired dropdown menu's second action from share to delete; adjusted className styling for subscription button and like count display.
Comment Section Component
src/components/base-ui/Admin/stories/comment_section.tsx
New client-side component managing nested comment tree state, delete confirmations, and report modals; recursively converts flat API comment data into hierarchical structure; wires user actions (create, edit, delete, report) to mutations with toast feedback.
Admin API Endpoints & Functions
src/lib/api/admin/endpoints/stories.ts, src/lib/api/admin/stories.ts
Added delete() and deleteComment() endpoint builders; added deleteAdminBookStory() and deleteAdminComment() API functions issuing DELETE requests; updated fetchAdminBookStoryDetail() to return data.result.

Sequence Diagram

sequenceDiagram
    actor User
    participant CommentSection
    participant DeleteModal
    participant API
    participant Server
    User->>CommentSection: Click delete comment
    CommentSection->>DeleteModal: Open confirmation dialog
    User->>DeleteModal: Confirm deletion
    DeleteModal->>API: deleteAdminComment(storyId, commentId)
    API->>Server: DELETE /api/admin/book-stories/{storyId}/comments/{commentId}
    Server-->>API: Success response
    API-->>CommentSection: Promise resolved
    CommentSection->>CommentSection: Remove comment from nested tree
    CommentSection->>User: Show success toast & update UI
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • 배포 최신화 #141: Overlapping admin story detail and comment functionality with shared API endpoints and component interactions.

Suggested labels

✨ feat

Poem

🐰 Comments now bend to the admin's will,
Nested trees pruned with a delete skill,
Confirmations pop, and APIs sing,
With reports and replies—what joy they bring! 🌿

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title '[feat] 관리자 책 이야기 및 댓글 삭제 api 연결' accurately describes the main changes: implementing delete API connections for admin stories and comments, which directly matches the pull request's core objective and all file modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/210-admin-api
📝 Coding Plan
  • Generate coding plan for human review comments

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

CodeRabbit can enforce grammar and style rules using `languagetool`.

Configure the reviews.tools.languagetool setting to enable/disable rules and categories. Refer to the LanguageTool Community to learn more.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

이 PR은 관리자 페이지에서 책 이야기 및 댓글을 삭제할 수 있는 기능을 구현합니다. 새로운 API 엔드포인트를 정의하고, 해당 API를 호출하는 함수를 추가했으며, UI 컴포넌트에 삭제 로직을 통합하여 관리자가 콘텐츠를 효율적으로 관리할 수 있도록 지원합니다.

Highlights

  • 관리자 책 이야기 삭제 기능 추가: 관리자가 책 이야기를 직접 삭제할 수 있는 기능이 추가되었으며, 관련 API가 연동되었습니다.
  • 관리자 댓글 삭제 기능 추가: 관리자가 책 이야기의 댓글을 삭제할 수 있는 기능이 추가되었으며, 관련 API가 연동되었습니다.
  • 관리자용 댓글 섹션 컴포넌트 분리: 기존 댓글 섹션 컴포넌트가 관리자 페이지 전용으로 분리되어 관리자 기능을 포함하도록 개선되었습니다.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

이 PR은 관리자가 책 이야기와 댓글을 삭제할 수 있는 API를 연동하는 작업을 담고 있습니다. 전반적으로 기능 구현은 잘 되었으나, 몇 가지 개선점을 제안합니다. 삭제 버튼의 아이콘이 기능과 일치하지 않는 점, 중복 코드를 줄일 수 있는 부분, 그리고 앞으로의 확장성을 고려했을 때 더 견고하게 만들 수 있는 로직에 대한 피드백을 포함했습니다. 코드 리뷰를 확인해주세요.

@nonoididnt
nonoididnt changed the base branch from main to dev March 20, 2026 05:27

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/components/base-ui/Admin/stories/bookstory_detail.tsx (1)

400-406: ⚠️ Potential issue | 🟡 Minor

Icon mismatch: using share icon for delete action.

The delete button uses /gray_share.svg (a share icon) while the action and alt text indicate deletion. Use the existing delete icon instead for visual consistency.

🎨 Suggested fix
                 <Image
-                  src="/gray_share.svg"
+                  src="/delete.svg"
                   alt="삭제"
                   width={20}
                   height={20}
                 />
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/components/base-ui/Admin/stories/bookstory_detail.tsx` around lines 400 -
406, The delete button is using the wrong icon: update the Image component that
renders the delete action (the Image with alt="삭제" and the adjacent "삭제하기" text)
to use the delete/trash icon asset instead of "/gray_share.svg"—replace the src
with the existing delete icon file (e.g., the project’s gray delete/trash SVG)
so the visual matches the action.
🧹 Nitpick comments (2)
src/lib/api/admin/stories.ts (2)

121-140: Same inconsistent error handling pattern as above.

Apply the same fix to check res.ok before parsing JSON for consistency and robustness.

♻️ Suggested fix
 export async function deleteAdminComment(
   bookStoryId: number,
   commentId: number
 ) {
   const res = await fetch(
     ADMIN_STORIES.deleteComment(bookStoryId, commentId),
     {
       method: "DELETE",
       credentials: "include",
     }
   );

+  if (!res.ok) {
+    const text = await res.text().catch(() => "");
+    throw new Error(`댓글 삭제 실패: ${res.status} ${text}`);
+  }
+
   const data: DeleteAdminCommentResponse = await res.json();

-  if (!res.ok || !data.isSuccess) {
+  if (!data.isSuccess) {
     throw new Error(data.message || "댓글 삭제에 실패했습니다.");
   }

   return data.result;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/api/admin/stories.ts` around lines 121 - 140, The deleteAdminComment
function currently calls await res.json() before verifying the HTTP response,
which can throw or mis-handle error bodies; change the flow in
deleteAdminComment to first check res.ok and, if not ok, read an error message
safely (e.g., try to parse JSON or use res.statusText) and throw an Error, only
calling await res.json() to produce DeleteAdminCommentResponse when res.ok is
true; reference the symbols deleteAdminComment, res, and
DeleteAdminCommentResponse when making the change.

99-112: Inconsistent error handling: JSON parsing before status check.

The delete functions parse JSON before checking res.ok, unlike fetchAdminBookStories (lines 35-40) which checks res.ok first. If the server returns a non-JSON error response (e.g., 500 with HTML body), res.json() will throw an unclear parsing error before reaching your custom error handling.

♻️ Suggested fix for consistent error handling
 export async function deleteAdminBookStory(bookStoryId: number) {
   const res = await fetch(ADMIN_STORIES.delete(bookStoryId), {
     method: "DELETE",
     credentials: "include",
   });

+  if (!res.ok) {
+    const text = await res.text().catch(() => "");
+    throw new Error(`책 이야기 삭제 실패: ${res.status} ${text}`);
+  }
+
   const data: DeleteAdminBookStoryResponse = await res.json();

-  if (!res.ok || !data.isSuccess) {
+  if (!data.isSuccess) {
     throw new Error(data.message || "책 이야기 삭제에 실패했습니다.");
   }

   return data.result;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/api/admin/stories.ts` around lines 99 - 112, The deleteAdminBookStory
function currently calls res.json() before checking res.ok which can throw on
non-JSON error responses; change the flow in deleteAdminBookStory (and use
ADMIN_STORIES.delete and DeleteAdminBookStoryResponse) to first check if
(!res.ok) — if not, read the response as text (or attempt json safely) and throw
an Error that includes status and the response body; only call res.json() and
validate data.isSuccess when res.ok is true, then return data.result.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/components/base-ui/Admin/stories/comment_section.tsx`:
- Around line 229-243: The current search loop in handleReportComment only
checks top-level comments and one level of replies (using c.replies.find), so
deeply nested replies are missed; implement a recursive search helper (e.g.,
findCommentById) that walks comments and their replies depth-first to locate the
Comment with the matching id, then replace the inline one-level logic that sets
targetComment with a call to this helper (operate on the same comments array and
return the found Comment or undefined), and use that result where targetComment
is referenced.
- Around line 132-134: The current useEffect synchronously calls setComments
when initialComments or storyAuthorNickname change, causing an extra render;
replace this derived state with useMemo by computing comments = useMemo(() =>
mapApiToUiComments(initialComments), [initialComments, storyAuthorNickname]) and
remove the useEffect/setComments pair (or, if you truly need local mutable
comments for operations like removeCommentById, initialize state once with
useState(() => mapApiToUiComments(initialComments)) and only update state via
those local mutators instead of resetting on every prop change); update
references to comments, setComments, mapApiToUiComments, initialComments,
storyAuthorNickname, and removeCommentById accordingly.
- Around line 7-10: The component mixes user and admin comment APIs causing
inconsistent behavior: update the code so all three operations use the same API
scope — either switch create/update to admin-scoped hooks or change
deleteAdminComment to call the user-scoped endpoint. Concretely, locate the
imports/use calls to useCreateCommentMutation and useUpdateCommentMutation in
comment_section.tsx and replace them with the corresponding admin mutations
(e.g., useAdminCreateCommentMutation / useAdminUpdateCommentMutation) and ensure
their hook implementations call the admin `/admin/...` endpoints, or
alternatively refactor deleteAdminComment to call the user `/book-stories/...`
endpoint and rename it to deleteComment to match the existing
useCreateCommentMutation/useUpdateCommentMutation semantics; update tests/types
and API clients accordingly to keep naming and endpoint usage consistent.

---

Outside diff comments:
In `@src/components/base-ui/Admin/stories/bookstory_detail.tsx`:
- Around line 400-406: The delete button is using the wrong icon: update the
Image component that renders the delete action (the Image with alt="삭제" and the
adjacent "삭제하기" text) to use the delete/trash icon asset instead of
"/gray_share.svg"—replace the src with the existing delete icon file (e.g., the
project’s gray delete/trash SVG) so the visual matches the action.

---

Nitpick comments:
In `@src/lib/api/admin/stories.ts`:
- Around line 121-140: The deleteAdminComment function currently calls await
res.json() before verifying the HTTP response, which can throw or mis-handle
error bodies; change the flow in deleteAdminComment to first check res.ok and,
if not ok, read an error message safely (e.g., try to parse JSON or use
res.statusText) and throw an Error, only calling await res.json() to produce
DeleteAdminCommentResponse when res.ok is true; reference the symbols
deleteAdminComment, res, and DeleteAdminCommentResponse when making the change.
- Around line 99-112: The deleteAdminBookStory function currently calls
res.json() before checking res.ok which can throw on non-JSON error responses;
change the flow in deleteAdminBookStory (and use ADMIN_STORIES.delete and
DeleteAdminBookStoryResponse) to first check if (!res.ok) — if not, read the
response as text (or attempt json safely) and throw an Error that includes
status and the response body; only call res.json() and validate data.isSuccess
when res.ok is true, then return data.result.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1141d252-60ea-4f45-92b4-d181be725c6c

📥 Commits

Reviewing files that changed from the base of the PR and between 498de60 and e1ced1e.

📒 Files selected for processing (5)
  • src/app/(admin)/admin/(app)/stories/[id]/page.tsx
  • src/components/base-ui/Admin/stories/bookstory_detail.tsx
  • src/components/base-ui/Admin/stories/comment_section.tsx
  • src/lib/api/admin/endpoints/stories.ts
  • src/lib/api/admin/stories.ts

Comment on lines +7 to +10
import {
useCreateCommentMutation,
useUpdateCommentMutation,
} from "@/hooks/mutations/useStoryMutations";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check what endpoints storyService uses for comment operations
ast-grep --pattern 'createComment($_, $_, $_) {
  $$$
}'

rg -n 'createComment|updateComment' src/services --type ts -A 3

Repository: checkmo2025/FE

Length of output: 557


🏁 Script executed:

# Check the full implementation of createComment and updateComment in storyService
sed -n '67,100p' src/services/storyService.ts

Repository: checkmo2025/FE

Length of output: 1260


🏁 Script executed:

# Find the useStoryMutations hook file
fd -t f "useStoryMutations" src/

Repository: checkmo2025/FE

Length of output: 98


🏁 Script executed:

# Inspect the Admin component file to see the context
head -n 20 src/components/base-ui/Admin/stories/comment_section.tsx

Repository: checkmo2025/FE

Length of output: 847


🏁 Script executed:

# Check lines 150-167 and 169-186 mentioned in the review
sed -n '150,186p' src/components/base-ui/Admin/stories/comment_section.tsx

Repository: checkmo2025/FE

Length of output: 811


🏁 Script executed:

# Find what STORY_ENDPOINTS.LIST is
rg "STORY_ENDPOINTS" src/ -A 2 | head -30

Repository: checkmo2025/FE

Length of output: 1547


🏁 Script executed:

# Inspect deleteAdminComment implementation
cat -n src/lib/api/admin/stories.ts | head -50

Repository: checkmo2025/FE

Length of output: 1565


🏁 Script executed:

# Check useStoryMutations to see if there are admin variants
cat -n src/hooks/mutations/useStoryMutations.ts

Repository: checkmo2025/FE

Length of output: 14166


🏁 Script executed:

# Find and check deleteAdminComment implementation
rg -n "deleteAdminComment" src/lib/api/admin/ -A 10

Repository: checkmo2025/FE

Length of output: 664


🏁 Script executed:

# Check if there are admin mutations for comments
fd "admin" src/hooks/mutations/ -t f

Repository: checkmo2025/FE

Length of output: 106


🏁 Script executed:

# Check the context of how deleteAdminComment is used in comment_section.tsx
rg -n "deleteAdminComment" src/components/base-ui/Admin/stories/comment_section.tsx -B 5 -A 5

Repository: checkmo2025/FE

Length of output: 977


🏁 Script executed:

# Check what STORY_ENDPOINTS.LIST resolves to
cat -n src/lib/api/endpoints/bookstory.ts

Repository: checkmo2025/FE

Length of output: 604


Admin component mixes user and admin APIs for comment operations.

The useCreateCommentMutation and useUpdateCommentMutation hooks use /book-stories/... endpoints (user-scoped), while deleteAdminComment uses the admin API endpoint. This creates an inconsistency where create and update operate on user endpoints but delete operates on admin endpoints.

Either migrate create/update to use admin-scoped endpoints (if admin-only mutations exist or should be created), or use user-scoped endpoints for all three operations if admins should have the same permissions as users for comments.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/components/base-ui/Admin/stories/comment_section.tsx` around lines 7 -
10, The component mixes user and admin comment APIs causing inconsistent
behavior: update the code so all three operations use the same API scope —
either switch create/update to admin-scoped hooks or change deleteAdminComment
to call the user-scoped endpoint. Concretely, locate the imports/use calls to
useCreateCommentMutation and useUpdateCommentMutation in comment_section.tsx and
replace them with the corresponding admin mutations (e.g.,
useAdminCreateCommentMutation / useAdminUpdateCommentMutation) and ensure their
hook implementations call the admin `/admin/...` endpoints, or alternatively
refactor deleteAdminComment to call the user `/book-stories/...` endpoint and
rename it to deleteComment to match the existing
useCreateCommentMutation/useUpdateCommentMutation semantics; update tests/types
and API clients accordingly to keep naming and endpoint usage consistent.

Comment on lines +132 to +134
useEffect(() => {
setComments(mapApiToUiComments(initialComments));
}, [initialComments, storyAuthorNickname]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Avoid calling setState synchronously within an effect.

ESLint correctly flags this pattern. When initialComments changes, synchronously setting state triggers an extra render. Since you're deriving state from props, consider using useMemo instead.

♻️ Suggested fix using useMemo
-  const [comments, setComments] = useState<Comment[]>(() =>
-    mapApiToUiComments(initialComments)
-  );
+  const derivedComments = useMemo(
+    () => mapApiToUiComments(initialComments),
+    [initialComments, storyAuthorNickname]
+  );
+  const [comments, setComments] = useState<Comment[]>(derivedComments);

-  useEffect(() => {
-    setComments(mapApiToUiComments(initialComments));
-  }, [initialComments, storyAuthorNickname]);
+  useEffect(() => {
+    setComments(derivedComments);
+  }, [derivedComments]);

Alternatively, if local mutations (like removeCommentById) aren't needed, you could derive comments entirely from useMemo without local state.

🧰 Tools
🪛 ESLint

[error] 133-133: Error: Calling setState synchronously within an effect can trigger cascading renders

Effects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:

  • Update external systems with the latest state from React.
  • Subscribe for updates from some external system, calling setState in a callback function when external state changes.

Calling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).

/home/jailuser/git/src/components/base-ui/Admin/stories/comment_section.tsx:133:5
131 |
132 | useEffect(() => {

133 | setComments(mapApiToUiComments(initialComments));
| ^^^^^^^^^^^ Avoid calling setState() directly within an effect
134 | }, [initialComments, storyAuthorNickname]);
135 |
136 | const removeCommentById = (

(react-hooks/set-state-in-effect)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/components/base-ui/Admin/stories/comment_section.tsx` around lines 132 -
134, The current useEffect synchronously calls setComments when initialComments
or storyAuthorNickname change, causing an extra render; replace this derived
state with useMemo by computing comments = useMemo(() =>
mapApiToUiComments(initialComments), [initialComments, storyAuthorNickname]) and
remove the useEffect/setComments pair (or, if you truly need local mutable
comments for operations like removeCommentById, initialize state once with
useState(() => mapApiToUiComments(initialComments)) and only update state via
those local mutators instead of resetting on every prop change); update
references to comments, setComments, mapApiToUiComments, initialComments,
storyAuthorNickname, and removeCommentById accordingly.

Comment on lines +229 to +243
let targetComment: Comment | undefined;

for (const c of comments) {
if (c.id === id) {
targetComment = c;
break;
}
if (c.replies) {
const found = c.replies.find((r) => r.id === id);
if (found) {
targetComment = found;
break;
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Shallow search may miss deeply nested replies.

handleReportComment only searches one level of replies (c.replies.find). If comments can be nested more deeply, this won't find the target comment.

🔧 Suggested fix with recursive search
   const handleReportComment = (id: number) => {
     if (!isLoggedIn) {
       openLoginModal();
       return;
     }

-    let targetComment: Comment | undefined;
-
-    for (const c of comments) {
-      if (c.id === id) {
-        targetComment = c;
-        break;
-      }
-      if (c.replies) {
-        const found = c.replies.find((r) => r.id === id);
-        if (found) {
-          targetComment = found;
-          break;
-        }
-      }
-    }
+    const findCommentById = (list: Comment[], targetId: number): Comment | undefined => {
+      for (const c of list) {
+        if (c.id === targetId) return c;
+        if (c.replies) {
+          const found = findCommentById(c.replies, targetId);
+          if (found) return found;
+        }
+      }
+      return undefined;
+    };
+
+    const targetComment = findCommentById(comments, id);

     if (targetComment) {
       setReportTargetNickname(targetComment.authorName);
       setIsReportModalOpen(true);
     }
   };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/components/base-ui/Admin/stories/comment_section.tsx` around lines 229 -
243, The current search loop in handleReportComment only checks top-level
comments and one level of replies (using c.replies.find), so deeply nested
replies are missed; implement a recursive search helper (e.g., findCommentById)
that walks comments and their replies depth-first to locate the Comment with the
matching id, then replace the inline one-level logic that sets targetComment
with a call to this helper (operate on the same comments array and return the
found Comment or undefined), and use that result where targetComment is
referenced.

@yhi9839
yhi9839 merged commit c4ea7b7 into dev Mar 20, 2026
4 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Mar 20, 2026
8 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Mar 30, 2026
8 tasks

This branch was successfully deployed

2 active deployments
Preview – check-mo — bbe5ea08 Deployed Mar 20, 2026 by vercel[bot]
Preview – checkmo — bbe5ea08 Deployed Mar 20, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[feat] 관리자 API 연결 작업

2 participants