Skip to content

Preserve in-progress quiz answers across modal close and reload - #48

Merged
rgajbhiyee merged 1 commit into
swciitg:mainfrom
adityamukesh:feature/persist-quiz-draft
Oct 27, 2026
Merged

rgajbhiyee merged 1 commit into
swciitg:mainfrom
adityamukesh:feature/persist-quiz-draft

Conversation

@adityamukesh

@adityamukesh adityamukesh commented Oct 22, 2026 •

Copy link
Copy Markdown

User description

Description

Closes #38

Quiz answers lived only in DailyQuiz component state, so a page refresh, accidental back-navigation, or closing the day modal threw away the attempt in progress.

What changes

  • DailyQuiz saves { step, answers } to sessionStorage under hs.quizDraft.<dayId> after each answer and restores it when the quiz mounts again (modal reopened or page reloaded). When a draft exists, the start screen shows "N of M answered", Resume Quiz, and Start over (which deletes the draft).
  • The draft is cleared only after a genuinely successful submit. ModuleDetail.handleDayAction used to catch and swallow submit errors, so DayModal couldn't tell success from failure; it now resolves true/false (the error banner behaviour is unchanged). On failure the full draft is kept so the attempt can be retried after reopening.
  • Quizzes already attempted (dailyQuizAttempt, from progress.attemptedQuizIds / quizScores) never restore a draft, and any leftover draft for them is deleted. The existing results view is unchanged.
  • Drafts are validated in frontend/src/utils/quizDraft.js. Malformed JSON, an unknown version, answers that aren't valid option indexes, a step that doesn't match the answers, or a quiz whose questions or options changed all fall back to a fresh attempt; the last check uses a fingerprint of question text and options, which also catches question-count changes. Storage errors (disabled storage, quota) are caught, so the quiz still works without a draft.
  • The draft is never sent to the server. The final submit sends the same answers array as before, and grading plus the one-attempt rule stay in quizController.submitQuiz.

Notes for reviewers

  • I kept the issue's choice of sessionStorage: it survives reloads and modal close, is scoped to the tab, and disappears when the tab closes.
  • Unchanged existing behaviour: when a submit fails, the modal still switches to the results view with a client-computed score (the error banner appears on the page behind the drawer). With this PR the answers are no longer lost in that case, and reopening the day offers Resume. I left that failure UI alone to keep this PR focused.
  • The repo has no test setup yet, so I added an npm test script in frontend/ that runs Node's built-in node --test runner. No new dependencies. It's easy to drop if you'd rather not have it.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Refactor / cleanup
  • Other (please describe)

How has this been tested?

AI assistance: this change was written with Claude Code (an AI coding agent), which also ran the checks and the browser walkthrough below.

Automated

  • cd frontend && npm test passes 14/14. The tests cover:

    • restoring a draft, including one saved after a failed final submit
    • per-day isolation and clearing
    • missing drafts, malformed JSON, non-object JSON and unknown versions
    • question count changed and question edited
    • invalid option indexes, an inconsistent step, and empty or oversized answer lists
    • storage that throws

    The same test file fails against main because the helper module doesn't exist there.

  • cd frontend && npm run build succeeds.

  • cd frontend && npm run lint fails, but identically on main and on this branch: 55 errors and 4 warnings, with no per-file differences. The new files lint clean. The one error reported in DayModal.jsx (react-hooks/set-state-in-effect) is the existing setViewMode("results") inside the effect.

End-to-end on a local stack (backend, a local MongoDB seeded with one module of two days, a 3-question quiz per day and a registered test user, and the Vite dev server)

  1. Answered 2 of 3 questions, did a full page reload, and reopened the day. The quiz tab showed "2 of 3 answered", Resume Quiz and Start over. Resume landed on Question 3 of 3.
  2. Stopped the backend and answered Q3. The submit failed (502, error banner shown) and the draft still held all 3 answers.
  3. Closed the modal with ✕ and reopened it: "3 of 3 answered". Restarted the backend, resumed and answered Q3. The submit succeeded, the server stored userAnswers: [1, 1, 2] (including the answers chosen before the reload) with a score of 15/20, and the draft was removed.
  4. Planted a draft for the already-attempted quiz and reloaded. The results view showed as before and the draft was deleted.
  5. A malformed draft ({not valid json) fell back to a fresh "Start Quiz".
  6. Answered Q1 and switched tabs: Resume (1 of 3) appeared. Start over returned to Question 1 of 3 and deleted the draft.
  7. Saved a draft, then edited that quiz's options in the DB and reloaded. The draft was ignored and a fresh "Start Quiz" showed.
  8. Checked the Resume / Start over view at 375px width.

No runtime errors appeared in the console. The only console entries were network 401s (this PR adds no requests) and the deliberate 502.

Screenshots

After a full page reload (step 1) Resume lands on Question 3 of 3
Quiz tab after reload showing 2 of 3 answered, Resume Quiz and Start over Quiz resumed at question 3 of 3
Results after the retried submit succeeded (step 3) Resume view at 375px (step 8)
Results view showing 15 of 20 points Resume Quiz and Start over at mobile width

Checklist

  • My branch is up to date with main
  • cd frontend && npm run lint passes (frontend changes): it fails on main with the same 55 errors and this PR adds no new lint problems (see above)
  • I updated README.md / backend/.env.example / frontend/.env.example if I changed setup, env vars, or API routes: n/a, no setup, env or API route changes
  • I did not commit secrets, .env files, or node_modules
  • UI changes were checked on mobile widths (375px, see step 8)
  • This PR references a related issue

🤖 Generated with Claude Code


CodeAnt-AI Description

Preserve unfinished quiz answers across modal closes and reloads

What Changed

  • Unsubmitted quiz answers are restored when reopening the quiz or reloading the page, with options to resume or start over.
  • Answers remain available after a failed submission and are cleared only after a successful submission.
  • Drafts are discarded for completed quizzes or when the quiz questions have changed.

Impact

✅ Fewer lost quiz attempts
✅ Faster retries after submission errors
✅ No stale answers on edited quizzes

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Save the selected answers and current step of an unsubmitted daily quiz
to sessionStorage (keyed by day id) and restore them when the quiz is
reopened, with "Resume Quiz" and "Start over" options on the start view.

The draft is only cleared once the server accepts the submission:
handleDayAction now resolves to true/false instead of swallowing the
error, so a failed submit keeps the answers for a retry. Drafts are also
dropped for quizzes already in progress.attemptedQuizIds, and drafts that
are malformed or were taken against a different version of the quiz are
ignored. The draft never goes to the server; grading and the one-attempt
rule stay in quizController.submitQuiz.

Adds node:test coverage for the draft helpers (npm test in frontend/).

Closes swciitg#38

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@adityamukesh
adityamukesh marked this pull request as ready for review October 22, 2026 18:03
@codeant-ai

codeant-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR ff91283 Oct 22, 2026 · 18:03 18:08

@codeant-ai

codeant-ai Bot commented Oct 22, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Oct 22, 2026
}

export function getQuizDraftKey(dayId) {
return `hs.quizDraft.${dayId}`;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: Because this key omits the user, another account using the same tab can see and resume the prior account’s saved answers for that day.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Security

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** frontend/src/utils/quizDraft.js
**Line:** 14:14
**Comment:**
	*Security: Because this key omits the user, another account using the same tab can see and resume the prior account’s saved answers for that day.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

@codeant-ai

codeant-ai Bot commented Oct 22, 2026

Copy link
Copy Markdown

CodeAnt Nitpicks

2 code suggestions

1. If the server saves the attempt but a later score update fails, this retains a draft that the server rejects as already attempted on retry.

Api mismatch · frontend/src/pages/ModuleDetail.jsx:246


2. When an unregistered learner finishes a quiz, this silently skips submission, while the quiz view still says it was completed although no attempt was recorded.

Api mismatch · frontend/src/pages/ModuleDetail.jsx:231

@codeant-ai

codeant-ai Bot commented Oct 22, 2026

Copy link
Copy Markdown

CodeAnt PR Risk: Medium Risk

  • The PR needs attention before merging.
  • Quiz drafts are keyed only by day ID, so another account using the same tab may see and resume the previous account’s saved answers.

Assessed commit: ff91283477cd

@adityamukesh

Copy link
Copy Markdown
Author

please review it

@adityamukesh

Copy link
Copy Markdown
Author

please review it.

@rgajbhiyee
rgajbhiyee merged commit 97aa8be into swciitg:main Oct 27, 2026
@rgajbhiyee

Copy link
Copy Markdown
Collaborator

Thank you @adityamukesh for your contribution, we request you to please register on https://swc.iitg.ac.in/hacktoberfest/ website

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

Labels

size:L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Preserve in-progress quiz answers across modal close and page refresh

2 participants