1
1
import { Box , VStack , Text , Button , useToast } from '@chakra-ui/react'
2
- import React , { FC , useState } from 'react'
2
+ import React , { FC , useState , Dispatch , SetStateAction } from 'react'
3
3
4
4
interface QuestionProps {
5
5
question : string
@@ -17,19 +17,26 @@ interface Question {
17
17
18
18
const Question : FC < QuestionProps > = ( props : QuestionProps ) => {
19
19
const question : Question = require ( `../../utils/questions/${ props . question } .json` )
20
- const [ optionSelected , setOptionSelected ] : [
21
- number ,
22
- React . Dispatch < React . SetStateAction < number > > ,
23
- ] = useState ( - 1 )
24
- const [ answersSubmitted , setAnswersSubmitted ] = useState ( false )
20
+ const [ optionsSelected , setOptionsSelected ] : [
21
+ number [ ] ,
22
+ Dispatch < SetStateAction < number [ ] > > ,
23
+ ] = useState ( [ - 1 ] )
25
24
const toast = useToast ( )
26
25
27
26
const selectAnswer = ( optionIndex : number ) => {
28
- setOptionSelected ( optionIndex )
27
+ if ( optionsSelected . indexOf ( optionIndex ) !== - 1 ) {
28
+ return setOptionsSelected (
29
+ optionsSelected . filter ( ( o ) => o !== optionIndex ) ,
30
+ )
31
+ }
32
+
33
+ setOptionsSelected (
34
+ [ ...optionsSelected , optionIndex ] . filter ( ( o ) => o !== - 1 ) , // Remove the -1 of the state initialization
35
+ )
29
36
}
30
37
31
38
const getOptionBackground = ( optionIndex : number ) => {
32
- if ( optionSelected == optionIndex ) {
39
+ if ( optionsSelected . indexOf ( optionIndex ) ! == - 1 ) {
33
40
return 'yellow.600'
34
41
}
35
42
return 'gray.600'
@@ -66,13 +73,23 @@ const Question: FC<QuestionProps> = (props: QuestionProps) => {
66
73
}
67
74
68
75
const submit = ( ) => {
69
- if ( optionSelected = == - 1 ) {
76
+ if ( optionsSelected . indexOf ( - 1 ) ! == - 1 ) {
70
77
return quizNotAnswered ( )
71
78
}
72
79
73
- if ( question . options [ optionSelected ] . correct ) {
74
- return quizSuccessToast ( )
75
- }
80
+ const correctAnswers = question . options . filter ( ( o ) => o . correct ) . length
81
+
82
+ let success = true
83
+ let correctAnswersCount = 0
84
+
85
+ optionsSelected . forEach ( ( o ) => {
86
+ if ( ! question . options [ o ] . correct ) success = false
87
+ correctAnswersCount ++
88
+ } )
89
+
90
+ if ( correctAnswers !== correctAnswersCount ) success = false
91
+
92
+ if ( success ) return quizSuccessToast ( )
76
93
77
94
return quizFailedToast ( )
78
95
}
0 commit comments