1+
2+ import React , { useState , useEffect } from 'react' ;
3+ import { View , Text , Button , StyleSheet } from 'react-native' ;
4+ import { useDispatch , useSelector } from 'react-redux' ;
5+ import { setQuestion , setScore , nextQuestion } from './redux/actions' ;
6+ import { questions } from './data/questions.json' ;
7+
8+ const QuizScreen = ( { navigation } ) => {
9+ const dispatch = useDispatch ( ) ;
10+ const currentQuestionIndex = useSelector ( ( state ) => state . currentQuestionIndex ) ;
11+ const score = useSelector ( ( state ) => state . score ) ;
12+
13+ const [ timer , setTimer ] = useState ( 30 ) ;
14+
15+ useEffect ( ( ) => {
16+ dispatch ( setQuestion ( questions [ 0 ] ) ) ;
17+ } , [ ] ) ;
18+
19+ useEffect ( ( ) => {
20+ if ( timer > 0 ) {
21+ const interval = setInterval ( ( ) => setTimer ( ( prev ) => prev - 1 ) , 1000 ) ;
22+ return ( ) => clearInterval ( interval ) ;
23+ }
24+ } , [ timer ] ) ;
25+
26+ const handleAnswer = ( selectedAnswer ) => {
27+ const correctAnswer = questions [ currentQuestionIndex ] . answer ;
28+ if ( selectedAnswer === correctAnswer ) {
29+ dispatch ( setScore ( score + 1 ) ) ;
30+ }
31+ dispatch ( nextQuestion ( ) ) ;
32+ } ;
33+
34+ const currentQuestion = questions [ currentQuestionIndex ] ;
35+
36+ return (
37+ < View style = { styles . container } >
38+ < Text style = { styles . question } > { currentQuestion . question } </ Text >
39+ { currentQuestion . options . map ( ( option , idx ) => (
40+ < Button key = { idx } title = { option } onPress = { ( ) => handleAnswer ( option ) } />
41+ ) ) }
42+ < Text > Time Remaining: { timer } s</ Text >
43+ </ View >
44+ ) ;
45+ } ;
46+
47+ const styles = StyleSheet . create ( {
48+ container : {
49+ flex : 1 ,
50+ justifyContent : 'center' ,
51+ alignItems : 'center' ,
52+ padding : 20 ,
53+ } ,
54+ question : {
55+ fontSize : 20 ,
56+ marginBottom : 20 ,
57+ } ,
58+ } ) ;
59+
60+ export default QuizScreen ;
61+
0 commit comments