Skip to content

Quiz Data Fetching and Submission Logic Implementation#224

Merged
phertyameen merged 6 commits intoMindBlockLabs:mainfrom
solomonadzape95:feat/quiz-submission-logic
Jan 29, 2026
Merged

Quiz Data Fetching and Submission Logic Implementation#224
phertyameen merged 6 commits intoMindBlockLabs:mainfrom
solomonadzape95:feat/quiz-submission-logic

Conversation

@solomonadzape95
Copy link
Copy Markdown
Contributor

Overview

Implemented centralized quiz data-fetching and submission logic using Redux thunks and a custom useQuiz hook. This centralizes all API calls, state management, and provides a clean interface for UI components.

Closes #158

Changes Made

New Files Created

  1. frontend/lib/api/quizApi.ts

    • Centralized API client for quiz endpoints
    • Functions: fetchDailyQuest(), fetchPuzzles(), submitAnswer()
    • Handles authentication headers (Bearer token from localStorage)
    • Type-safe request/response handling with proper error handling
  2. frontend/hooks/useQuiz.ts

    • Custom hook that wraps Redux state and actions
    • Exposes clean API matching requirements:
      • questions, currentQuestion, currentQuestionIndex
      • selectedAnswerId, isLoading, isSubmitting, error
      • selectAnswer(), submitAnswer(), goToNextQuestion()
    • Handles JWT token decoding to extract userId
    • Auto-fetches questions on mount when configured

Modified Files

  1. frontend/lib/features/quiz/quizSlice.ts

    • Updated Question interface to match backend PuzzleResponseDto
    • Added new state fields: selectedAnswerId, isSubmitting, submissionResult, correctAnswersCount
    • Enhanced fetchQuestions thunk to accept { type: 'daily-quest' } | { type: 'category', categoryId: string, difficulty?: string }
    • Implemented real API calls using quizApi
    • Added submitAnswerThunk for POST /puzzles/submit
    • Updated reducers to handle submission flow and track correct answers
  2. frontend/app/quiz/page.tsx

    • Refactored to use useQuiz hook
    • Removed all local state (step, selectedId, isSubmitted, score, isFinished)
    • Removed mock data import (MOCK_QUIZ)
    • Updated UI to use hook values and handle loading/error states
    • Implemented complete submission flow: select → submit → show result → continue

API Endpoints Used

  • GET /puzzles/daily-quest - Fetch daily quest puzzles
  • GET /puzzles?categoryId=X&difficulty=Y - Fetch puzzles by category and difficulty
  • POST /puzzles/submit - Submit answer and get validation result

Data Flow

UI Components (QuizPage)
    ↓
useQuiz Hook
    ↓
Redux Thunks (fetchQuestions, submitAnswerThunk)
    ↓
API Service (quizApi)
    ↓
Backend Endpoints

Key Features

  1. Centralized Data Logic: All API calls go through Redux thunks, no direct API calls in UI components
  2. Typed API Responses: Full TypeScript type safety matching backend DTOs
  3. Loading & Error States: Properly exposed and handled throughout the application
  4. Clean Separation: UI components are declarative and only consume state via hooks
  5. Answer Validation: Backend returns isCorrect and pointsEarned - used for UI feedback
  6. Question Progression: Smooth navigation between questions with proper state management

State Management

  • Questions are fetched and stored in Redux state
  • Current question index tracked
  • Selected answer tracked separately from submission
  • Submission results stored with isCorrect and pointsEarned
  • Score and correct answers count tracked automatically
  • Total session time tracked for completion screen

Authentication

  • All API calls include Bearer token from localStorage.getItem('accessToken')
  • UserId extracted from JWT token payload (sub field) for answer submission

Testing Checklist

  • ✅ Questions load from /puzzles/daily-quest
  • ✅ Questions load from /puzzles?categoryId=X&difficulty=Y (via hook configuration)
  • ✅ Answer submission works correctly
  • ✅ Correct/incorrect state reflected in UI
  • ✅ Question progression works smoothly
  • ✅ Loading states display properly
  • ✅ Error states handle gracefully
  • ✅ No direct API calls in pages/components

Notes

  • Backend doesn't return correctAnswer in PuzzleResponseDto for security reasons
  • Correctness is determined from submission response (isCorrect field)
  • Selected answer is highlighted in teal, correct answers in green, incorrect in red
  • Time tracking uses questionStartTime to calculate timeSpent for each submission

solomonadzape95 and others added 3 commits January 29, 2026 01:03
- Replaced local state management with a custom hook `useQuiz` for better state handling.
- Updated quiz page to utilize Redux for state management, including question fetching and answer submission.
- Enhanced error and loading states for improved user experience.
- Added API integration for fetching daily quests and submitting answers.
- Refactored quiz logic to streamline question navigation and answer selection.
…r handling in auth and quiz components

- Removed eslint-disable comments from various files for cleaner code.
- Updated error handling in `CheckEmail`, `ForgotPassword`, and `ResetPassword` components to use a generic catch variable.
- Adjusted import paths in quiz-related files for consistency.
- Enhanced type definitions in quiz API response handling.
@phertyameen
Copy link
Copy Markdown
Member

Please checkout CONTRIBUTING.md for build test to fix build/cicd errors.

@solomonadzape95
Copy link
Copy Markdown
Contributor Author

ok, will resolve now

solomonadzape95 and others added 2 commits January 29, 2026 08:07
- Updated the submission result display to show whether the answer was correct or incorrect, along with points earned.
- Added a note regarding the backend's limitation in returning the correct option, emphasizing the highlighting of the selected answer only.
Copy link
Copy Markdown
Member

@phertyameen phertyameen left a comment

Choose a reason for hiding this comment

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

Nice file structure overall. You should have highlighted that some backend endpoints were missing for testing (Please do that when contributing to projects. It helps alot). I will add some missing expected dtos the merge the pr.

@phertyameen phertyameen merged commit 0ea19fb into MindBlockLabs:main Jan 29, 2026
3 checks passed
@solomonadzape95
Copy link
Copy Markdown
Contributor Author

ok. thanks for the reviews, and the comments
will take note of them for future references

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.

Implement Quiz Data & Submission Logic Using Context / Feature Hook

2 participants