1- import { useState } from 'react' ;
1+ import { useEffect } from 'react' ;
22import { Box , Button , Paper , Typography } from '@mui/material' ;
3+ import { useSearchParams } from 'react-router-dom' ;
34import './App.css' ;
45import { QuizQuestion } from './components/QuizQuestion' ;
56import { QuizStats } from './components/QuizStats' ;
@@ -11,20 +12,32 @@ export function App() {
1112 const correctQuestions = useQuizStore ( ( state ) => state . correctQuestions ) ;
1213 const resetProgress = useQuizStore ( ( state ) => state . resetProgress ) ;
1314
14- const [ currentQuestionId , setCurrentQuestionId ] = useState (
15- ( ) => selectNextQuestion ( answeredQuestions , correctQuestions ) ?? questionIds [ 0 ] ,
16- ) ;
15+ const [ searchParams , setSearchParams ] = useSearchParams ( ) ;
16+
17+ const urlQuestionId = searchParams . get ( 'q' ) ;
18+ const validUrlQuestionId = urlQuestionId && questionIds . includes ( urlQuestionId ) ? urlQuestionId : null ;
19+
20+ const currentQuestionId =
21+ validUrlQuestionId ?? selectNextQuestion ( answeredQuestions , correctQuestions ) ?? questionIds [ 0 ] ;
22+
23+ // Sync URL with current question
24+ useEffect ( ( ) => {
25+ if ( searchParams . get ( 'q' ) !== currentQuestionId ) {
26+ setSearchParams ( { q : currentQuestionId } , { replace : true } ) ;
27+ }
28+ } , [ currentQuestionId , searchParams , setSearchParams ] ) ;
1729
1830 const handleNextQuestion = ( ) => {
1931 const nextId = selectNextQuestion ( answeredQuestions , correctQuestions ) ;
2032 if ( nextId ) {
21- setCurrentQuestionId ( nextId ) ;
33+ setSearchParams ( { q : nextId } , { replace : true } ) ;
2234 }
2335 } ;
2436
2537 const handlePlayAgain = ( ) => {
2638 resetProgress ( ) ;
27- setCurrentQuestionId ( questionIds [ Math . floor ( Math . random ( ) * questionIds . length ) ] ) ;
39+ const randomId = questionIds [ Math . floor ( Math . random ( ) * questionIds . length ) ] ;
40+ setSearchParams ( { q : randomId } , { replace : true } ) ;
2841 } ;
2942
3043 const allQuestionsCorrect = correctQuestions . length === questionIds . length ;
0 commit comments