Skip to content

fix(web): surface paper stats loading errors#141

Merged
is0692vs merged 5 commits intomainfrom
split/pr138-paper-stats-feedback
Mar 18, 2026
Merged

fix(web): surface paper stats loading errors#141
is0692vs merged 5 commits intomainfrom
split/pr138-paper-stats-feedback

Conversation

@is0692vs
Copy link
Contributor

@is0692vs is0692vs commented Mar 17, 2026

Summary

  • keep the author stats loading indicator active until the async fetch really settles
  • prevent state updates after unmount during the stats fetch effect
  • surface fetch failures through statsError so authors see why stats are unavailable

Validation

  • npm run --workspace apps/web typecheck

Split out of #138 to keep review scoped to the paper detail stats UX fix.

Greptile Summary

このPRは2つの独立した改善をまとめています:(1) paper-detail-client.tsx における fetchStats のリファクタリングでエラーハンドリングとローディング状態の管理を改善、(2) users.ts の検索キャッシュを真の LRU(Least Recently Used)実装に改善し、テストを高速化。

主な変更点:

  • fetchStats が HTTP エラーステータス(401/403/404 など)を statsError ステートに反映するよう改善
  • エラー発生時に setStats(null) を呼び出し、古いデータとエラーメッセージが同時表示される問題を修正
  • mountedRefisCancelled コールバックを組み合わせた canUpdateState でアンマウント後のステート更新を防止
  • applyCountedView からの再フェッチが withLoading: false でサイレント実行されるよう変更し、既存のローディング状態を上書きしない意図を明示
  • getCachedResults でキャッシュヒット時に Map の末尾へ再挿入することで真の LRU 昇格を実装
  • キャッシュ上限テストを MAX_CACHE_SIZE=3 の小さなキャッシュで再実装し、1002 リクエスト送信を廃止

指摘事項:

  • finally ブロックが withLoading: false のフェッチ完了時にも setStatsLoading(false) を呼び出すため、初回ロードと再フェッチが並行した場合にローディングインジケーターが早期消灯してしまう可能性がある

Confidence Score: 3/5

  • エラーハンドリングの改善は適切だが、finally ブロックの条件不足によりローディング状態の競合が残っておりマージ前の修正を推奨
  • API 側(users.ts / users.test.ts / types.ts)の変更は正確で問題なし。Web 側(paper-detail-client.tsx)は全体的な方向性は正しいが、withLoading: false フェッチの finally ブロックが setStatsLoading(false) を無条件に呼び出す点で、初回ロードとの競合時にローディング UI が早期に消えるバグが残っている。
  • apps/web/src/app/papers/[id]/paper-detail-client.tsx の finally ブロック(185行目)に注意

Important Files Changed

Filename Overview
apps/web/src/app/papers/[id]/paper-detail-client.tsx fetchStats を大幅にリファクタリングし、ローディング/エラー状態を適切に管理するよう改善。ただし、finally ブロックが withLoading: false 時でも setStatsLoading(false) を呼び出すため、並行フェッチが発生した際にローディングインジケーターが早期に消えるバグが残っている。
apps/api/src/routes/users.ts getCachedResults でキャッシュヒット時に再挿入(MRU 昇格)する LRU 実装を追加。setCachedResults にテスト用の maxSize オーバーライドパラメータを追加。実装は正しい。
apps/api/src/routes/tests/users.test.ts キャッシュ上限テストを MAX_CACHE_SIZE=3 の小さなキャッシュで書き直し、MRU 昇格・LRU 退出の両方を検証するよう改善。テストロジックは正しく、1002 リクエスト送信の非効率なアプローチを廃止。
apps/api/src/types.ts Env 型に MAX_CACHE_SIZE?: string を追加。変更は最小限で正確。

Sequence Diagram

sequenceDiagram
    participant C as PaperDetailClient
    participant E1 as useEffect(stats)
    participant E2 as useEffect(view tracking)
    participant API as API Server

    C->>E1: paper.id が確定
    E1->>C: fetchStats({ withLoading: true })
    C->>C: statsLoading = true
    C->>API: GET /api/papers/:id/stats

    C->>E2: paper.id が確定
    E2->>API: POST /api/papers/:id/views
    API-->>E2: { counted: true }
    E2->>C: applyCountedView()
    C->>C: publicViewCount + 1
    C->>C: fetchStats({ withLoading: false }) ← サイレント再フェッチ
    C->>API: GET /api/papers/:id/stats

    Note over C,API: バックグラウンドフェッチが先に完了した場合
    API-->>C: stats data (再フェッチ)
    C->>C: finally: setStatsLoading(false) ⚠️ 初回ロード中なのに false に
    API-->>C: stats data (初回フェッチ)
    C->>C: setStats(data)
    C->>C: finally: setStatsLoading(false)
Loading
Prompt To Fix All With AI
This is a comment left during a code review.
Path: apps/web/src/app/papers/[id]/paper-detail-client.tsx
Line: 184-186

Comment:
**`withLoading: false` でもローディング状態を強制リセットしてしまう**

`finally` ブロックは `withLoading` の値に関係なく `setStatsLoading(false)` を呼び出します。これにより、`applyCountedView` から `fetchStats({ withLoading: false })` が呼ばれた場合、初回の `fetchStats({ withLoading: true })` がまだ実行中であっても、バックグラウンド再フェッチが先に完了した時点でローディングインジケーターが消えてしまいます。

**具体的なシナリオ:**
1. ページ読み込み時に `fetchStats({ withLoading: true })` が実行 → `statsLoading = true`
2. 閲覧記録が完了し、`applyCountedView``fetchStats({ withLoading: false })` が実行
3. バックグラウンドフェッチ(手順2)が先に完了 → `finally: setStatsLoading(false)` によりスピナーが消える
4. 初回フェッチ(手順1)はまだ進行中なのにローディング表示がなくなる

`withLoading``true` のときだけ `setStatsLoading(false)` を呼ぶよう条件を追加することを推奨します:

```suggestion
      } finally {
        if ((options?.withLoading ?? true) && canUpdateState()) setStatsLoading(false);
      }
```

How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: a89a874

@vercel
Copy link

vercel bot commented Mar 17, 2026

Deployment failed with the following error:

Resource is limited - try again in 24 hours (more than 100, code: "api-deployments-free-per-day").

Learn More: https://vercel.com/hirokis-projects-afd618c7?upgradeToPro=build-rate-limit

@gemini-code-assist
Copy link
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!

This pull request significantly enhances the robustness and user experience of the paper statistics display. It ensures that users receive clear feedback when statistics fail to load, provides more accurate loading state indications, and prevents common issues related to asynchronous operations and component lifecycle management in React.

Highlights

  • Improved Error Handling: Implemented specific error messages for different API response statuses (401, 403, 404) when fetching paper statistics, providing clearer feedback to users.
  • Enhanced Loading State Management: Adjusted the loading indicator logic to remain active until the asynchronous fetch operation for paper statistics has fully settled, ensuring a more accurate user experience.
  • Prevented State Updates on Unmount: Added a cleanup mechanism within the useEffect hook to prevent state updates from occurring after the component has unmounted, addressing potential memory leaks and warnings.
Changelog
  • apps/web/src/app/papers/[id]/paper-detail-client.tsx
    • Added detailed error handling for API responses (401, 403, 404, and generic failures) when fetching paper stats, setting specific statsError messages.
    • Modified the useEffect hook to correctly manage the statsLoading state, ensuring it remains true until the fetchStats promise resolves or rejects, and introduced a cancelled flag to prevent state updates on unmount.
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.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

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.

Copy link
Contributor

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

Choose a reason for hiding this comment

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

Code Review

This pull request improves the user experience by handling and surfacing errors from the paper stats API call. It also correctly keeps the loading indicator active until the fetch is complete and attempts to prevent state updates on unmounted components.

I've left a couple of comments for improvement:

  • A suggestion to deduplicate a repeated error string for better maintainability.
  • A more critical point about the incomplete implementation of the cancellation logic, which doesn't fully prevent state updates on unmount as intended.

Additionally, while the error handling logic has been added, there are no corresponding tests to verify these new error states. Adding tests for API failures (e.g., 401, 403, 404 responses) would make this change more robust and prevent future regressions.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

Warning

Rate limit exceeded

@is0692vs has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 23 minutes and 10 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: b763783e-0516-4aed-8cf5-56f35a70e640

📥 Commits

Reviewing files that changed from the base of the PR and between f852003 and a89a874.

📒 Files selected for processing (4)
  • apps/api/src/routes/__tests__/users.test.ts
  • apps/api/src/routes/users.ts
  • apps/api/src/types.ts
  • apps/web/src/app/papers/[id]/paper-detail-client.tsx
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch split/pr138-paper-stats-feedback
📝 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.

@pull-request-size pull-request-size bot added size/L and removed size/S labels Mar 17, 2026
@is0692vs is0692vs merged commit ee324c0 into main Mar 18, 2026
17 of 18 checks passed
@is0692vs is0692vs deleted the split/pr138-paper-stats-feedback branch March 18, 2026 01:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant