Skip to content

fix: prevent problem refetch on language switch#30

Open
pavsoss wants to merge 4 commits into
Rishabhworkspace:mainfrom
pavsoss:lang-switch-refetch
Open

fix: prevent problem refetch on language switch#30
pavsoss wants to merge 4 commits into
Rishabhworkspace:mainfrom
pavsoss:lang-switch-refetch

Conversation

@pavsoss

@pavsoss pavsoss commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Closes #7

Summary

Fixes an issue where switching programming languages in the Problem Workspace triggered a full problem re-fetch from the backend, causing unnecessary network requests and loading state flashes.

Changes Made

  • Split the existing useEffect in ProblemWorkspace.tsx into two separate effects.
  • Added a dedicated effect to fetch problem data only when problemId changes.
  • Added a separate effect to handle language changes and update editor code state.
  • Moved boilerplate and localStorage initialization logic into the language-change effect.
  • Removed language from the problem-fetch effect dependency array.
  • Preserved language-specific code loading from localStorage.

Expected Behavior

Language Switch

  • No requests are made to /api/content/problems/:id.
  • No loading spinner appears.
  • Editor code updates seamlessly to the saved code or default boilerplate for the selected language.

Problem Change

  • Problem data is fetched normally when problemId changes.
  • Problem content and metadata are updated correctly.

Verification

  • Verified that switching languages triggers zero additional problem API requests.
  • Verified that no loading state is shown when changing languages.
  • Verified that saved code is loaded correctly from localStorage for each language.
  • Verified that default boilerplate is loaded when no saved code exists.
  • Verified that problem data is fetched only when navigating to a different problem.

Summary by CodeRabbit

  • New Features

    • Editor now uses a fixed readable font size (14px).
  • Improvements

    • More reliable per-language saved-code loading.
    • Reorganized editor header controls and improved layout.
  • Bug Fixes

    • User-facing error notifications when problem data or code execution fail; loading and execution states handled more reliably.
  • Documentation

    • Expanded JSDoc documentation for content and controller APIs and rate-limiting middleware.

@vercel

vercel Bot commented Jun 8, 2026

Copy link
Copy Markdown

@pavsoss is attempting to deploy a commit to the rishabhjtripathi2903-3434's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

ProblemWorkspace separates problem fetching (runs on problemId) from language-specific code loading (runs on problemId + language), removes the font-size slider and fixes editor fontSize to 14, reforms Run/execute handling, and adds JSDoc to frontend content API, backend controllers, and the rate limiter.

Changes

Workspace and documentation updates

Layer / File(s) Summary
Problem fetch and per-language code effects
app/src/sections/ProblemWorkspace.tsx
Problem fetch moved to a useEffect that depends only on problemId; saved per-language code loading (from localStorage or language boilerplate) moved to a separate useEffect depending on problemId + language, with toast error and loading cleanup.
Editor UI, execution, and minor markup
app/src/sections/ProblemWorkspace.tsx
Run Code button className reformatted; handleRunCode initializes executionResult to "Running...", sets isExecuting, handles errors with toast.error, and resets state in finally. Removed font-size slider from header and set Monaco editor options.fontSize to 14; small spacing/blank-line markup changes and a submit-handler JSDoc were added.
Frontend content API JSDoc
app/src/api/content.ts
Added JSDoc blocks for exported content-fetching functions and for the internal getAuthHeader helper; no behavior or signatures changed.
Backend controllers JSDoc
backend/src/controllers/contentController.ts
Expanded JSDoc for content controllers (routes, params, responses, and executeCode validation); no controller logic or signatures changed.
Rate limiter JSDoc
backend/src/middleware/rateLimiter.ts
Inserted JSDoc describing executionRateLimiter requester key generation and exceeded-request handler; limiter logic unchanged.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped through code with careful paws,

Split effects so fetch won’t cause a pause.
Fonts are steady, run shows "Running..." true,
Docs + comments bloom — concise and new.
A tiny rabbit clap for this tidy review.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Additional changes beyond the core fix include JSDoc documentation additions across multiple files and UI reformatting (button className, font-size hardcoding, header layout); these are scope creep from the stated objective. Consider separating documentation and UI refactoring into distinct PRs to maintain focused changeset; the core fix and documentation changes should be evaluated independently.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the primary fix: preventing unnecessary problem refetching when users switch programming languages.
Linked Issues check ✅ Passed The PR successfully implements all required coding objectives from issue #7: splitting the useEffect into two separate effects (one for problemId, one for language), removing language from problem-fetch dependency array, and preserving localStorage code loading.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
app/src/sections/ProblemWorkspace.tsx (1)

30-40: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Clear stale problem state before/after failed fetches.

When a fetch fails for a new problemId, problem retains the previous value (Line 35 only sets on success), so the UI can show the wrong problem after loading ends.

Suggested fix
  useEffect(() => {
    const fetchProblem = async () => {
      try {
        setLoading(true);
+       setProblem(null);
        const data = await getProblemById(problemId);
        setProblem(data);
      } catch {
+       setProblem(null);
        toast.error('Failed to load problem');
      } finally {
        setLoading(false);
      }
    };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/src/sections/ProblemWorkspace.tsx` around lines 30 - 40, The fetch logic
in useEffect's fetchProblem leaves the previous problem in state on failures;
update fetchProblem to clear stale state by calling setProblem(null) before
starting the fetch (or in the catch block) so the UI doesn't display the old
problem for a new problemId, while still using setLoading(true/false) and
keeping the toast.error call on failure (refer to useEffect, fetchProblem,
setProblem, setLoading, problemId, and toast.error to locate the change).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/src/sections/ProblemWorkspace.tsx`:
- Around line 46-61: The effect that loads saved code (useEffect) depends only
on language but reads localStorage key keyed by problemId, so navigating to a
different problem with the same language keeps stale code; update the dependency
array to include problemId as well so the effect re-runs when problemId changes,
ensuring localStorage.getItem(`code_${problemId}_${language}`) and the
subsequent setCode(...) (including the boilerplate fallback) run for the new
problem.

---

Outside diff comments:
In `@app/src/sections/ProblemWorkspace.tsx`:
- Around line 30-40: The fetch logic in useEffect's fetchProblem leaves the
previous problem in state on failures; update fetchProblem to clear stale state
by calling setProblem(null) before starting the fetch (or in the catch block) so
the UI doesn't display the old problem for a new problemId, while still using
setLoading(true/false) and keeping the toast.error call on failure (refer to
useEffect, fetchProblem, setProblem, setLoading, problemId, and toast.error to
locate the change).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: aa2167fe-e5ff-4851-ba4f-74fbc3c5df23

📥 Commits

Reviewing files that changed from the base of the PR and between 9359a5f and 34e2741.

📒 Files selected for processing (1)
  • app/src/sections/ProblemWorkspace.tsx

Comment thread app/src/sections/ProblemWorkspace.tsx Outdated
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

@coderabbitai coderabbitai 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.

Caution

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

⚠️ Outside diff range comments (1)
app/src/sections/ProblemWorkspace.tsx (1)

220-220: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove conflicting text size class.

Line 220 has both text-xs and text-xl classes on the same element. Only one font-size utility should be present. Based on the intent to show a larger "A" label (compared to the smaller one on line 212), keep text-xl and remove text-xs.

🎨 Proposed fix
-                <span className="text-white/40 text-xs text-xl">A</span>
+                <span className="text-white/40 text-xl">A</span>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/src/sections/ProblemWorkspace.tsx` at line 220, In ProblemWorkspace.tsx
locate the span rendering the "A" label (the span with classes "text-white/40
text-xs text-xl") and remove the conflicting font-size utility by deleting
"text-xs" so only "text-xl" remains; ensure the span retains its color class
("text-white/40") and any other classes untouched.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@app/src/sections/ProblemWorkspace.tsx`:
- Line 220: In ProblemWorkspace.tsx locate the span rendering the "A" label (the
span with classes "text-white/40 text-xs text-xl") and remove the conflicting
font-size utility by deleting "text-xs" so only "text-xl" remains; ensure the
span retains its color class ("text-white/40") and any other classes untouched.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c3f7db8b-6fb3-4b2c-ac02-81b34b3d90da

📥 Commits

Reviewing files that changed from the base of the PR and between 34e2741 and 79063de.

📒 Files selected for processing (1)
  • app/src/sections/ProblemWorkspace.tsx

@Rishabhworkspace

Copy link
Copy Markdown
Owner

@pavsoss check for coderabbit suggestion

@pavsoss

pavsoss commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

@Rishabhworkspace implemented the coderabbit suggestions

@vercel

vercel Bot commented Jun 9, 2026

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
algo-forge-2-0 Ready Ready Preview, Comment Jun 9, 2026 12:09pm

@coderabbitai coderabbitai 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.

Caution

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

⚠️ Outside diff range comments (2)
app/src/sections/ProblemWorkspace.tsx (2)

119-125: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Avoid claiming submission persistence before it succeeds.

Line 120 shows “Submission saved” before updateProblemStatus completes, but failures are swallowed, so users can get a false success message.

Suggested fix
    if (res?.success && res?.allPassed) {
-     toast.success('All test cases passed! (Submission saved)');
+     toast.success('All test cases passed!');
      try {
        await updateProblemStatus(problemId, 'SOLVED');
+       toast.success('Submission saved');
      } catch (err) {
        // silently fail if not logged in or other issues
      }
    }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/src/sections/ProblemWorkspace.tsx` around lines 119 - 125, The success
toast currently claims "Submission saved" before updateProblemStatus(problemId,
'SOLVED') completes and any errors are swallowed; change the flow so the toast
is shown only after updateProblemStatus resolves successfully (or alternatively
show a more conservative message like "All test cases passed!" immediately and
only append "Submission saved" after updateProblemStatus succeeds), and surface
failures from updateProblemStatus by catching errors and calling toast.error (or
reverting UI state) instead of silently ignoring them; update the code around
res, toast.success, updateProblemStatus, and problemId accordingly.

37-47: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reset stale problem state on fetch failure.

When loading a new problemId fails, the previous problem can remain visible because problem is never cleared in the failure path.

Suggested fix
  useEffect(() => {
    const fetchProblem = async () => {
      try {
        setLoading(true);
+       setProblem(null);
        const data = await getProblemById(problemId);
        setProblem(data);
      } catch {
+       setProblem(null);
        toast.error('Failed to load problem');
      } finally {
        setLoading(false);
      }
    };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/src/sections/ProblemWorkspace.tsx` around lines 37 - 47, The fetchProblem
useEffect currently leaves the previous problem visible on failure; update
fetchProblem (or the surrounding effect) to clear stale state by calling
setProblem(null) when starting a new load (before the try) or in the catch block
where toast.error is called, ensuring setLoading(false) remains in finally;
reference the useEffect/fetchProblem closure and the setProblem setter to
implement this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@app/src/sections/ProblemWorkspace.tsx`:
- Around line 119-125: The success toast currently claims "Submission saved"
before updateProblemStatus(problemId, 'SOLVED') completes and any errors are
swallowed; change the flow so the toast is shown only after updateProblemStatus
resolves successfully (or alternatively show a more conservative message like
"All test cases passed!" immediately and only append "Submission saved" after
updateProblemStatus succeeds), and surface failures from updateProblemStatus by
catching errors and calling toast.error (or reverting UI state) instead of
silently ignoring them; update the code around res, toast.success,
updateProblemStatus, and problemId accordingly.
- Around line 37-47: The fetchProblem useEffect currently leaves the previous
problem visible on failure; update fetchProblem (or the surrounding effect) to
clear stale state by calling setProblem(null) when starting a new load (before
the try) or in the catch block where toast.error is called, ensuring
setLoading(false) remains in finally; reference the useEffect/fetchProblem
closure and the setProblem setter to implement this change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 107db789-62d5-487d-9175-69478f698c93

📥 Commits

Reviewing files that changed from the base of the PR and between 79063de and 4b5f949.

📒 Files selected for processing (4)
  • app/src/api/content.ts
  • app/src/sections/ProblemWorkspace.tsx
  • backend/src/controllers/contentController.ts
  • backend/src/middleware/rateLimiter.ts
✅ Files skipped from review due to trivial changes (3)
  • backend/src/middleware/rateLimiter.ts
  • app/src/api/content.ts
  • backend/src/controllers/contentController.ts

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.

Language Switch in Problem Workspace Re-fetches the Entire Problem

2 participants