Skip to content

Commit

Permalink
Update Questions.tsx
Browse files Browse the repository at this point in the history
Show result
  • Loading branch information
Ibrahim-Halil-Kuray committed Oct 29, 2023
1 parent ee95df1 commit 6432e0a
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions src/components/Questions.tsx
Expand Up @@ -18,6 +18,7 @@ const Questions: React.FC<QuestionsProps> = ({ apiUrl }) => {
const [isTimeUp, setIsTimeUp] = useState<boolean>(false);
const [isAnswered, setIsAnswered] = useState<boolean>(false);
const [timer, setTimer] = useState<number>(0);
const [showResults, setShowResults] = useState<boolean>(false);

useEffect(() => {
fetch(apiUrl)
Expand Down Expand Up @@ -52,8 +53,9 @@ const Questions: React.FC<QuestionsProps> = ({ apiUrl }) => {
return () => {
clearInterval(interval);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [timer, currentQuestionIndex, questions, isTimeUp]);

const handleAnswerQuestion = (selectedOption: number) => {
const correctAnswer = questions[currentQuestionIndex].correct_answer;
setUserAnswers([...userAnswers, selectedOption === correctAnswer ? 1 : 0]);
Expand All @@ -65,15 +67,30 @@ const Questions: React.FC<QuestionsProps> = ({ apiUrl }) => {
setCurrentQuestionIndex(currentQuestionIndex + 1);
setIsAnswered(false);
} else {
// Show result
setShowResults(true);
}
};

const renderResults = () => {
const correctAnswers = userAnswers.filter((answer) => answer === 1).length;
const wrongAnswers = userAnswers.filter((answer) => answer === 0).length;

return (
<div>
<h1>You have answered all questions</h1>
<p>Correct answers: {correctAnswers}</p>
<p>Wrong answers: {wrongAnswers}</p>
</div>
);
};

return (
<div>
{timer > 0 && !isTimeUp && <p>Timer: {timer} second</p>}

{questions.length > 0 && currentQuestionIndex < questions.length ? (
{showResults ? (
renderResults()
) : questions.length > 0 && currentQuestionIndex < questions.length ? (
<div>
<h1>Question {currentQuestionIndex + 1}</h1>
<p>{questions[currentQuestionIndex].question}</p>
Expand Down Expand Up @@ -105,14 +122,7 @@ const Questions: React.FC<QuestionsProps> = ({ apiUrl }) => {
</div>
) : (
<div>
<h1>You have have answred all question</h1>
<p>
Correct answers:{' '}
{userAnswers.filter((answer) => answer === 1).length}
</p>
<p>
Wrong answers: {userAnswers.filter((answer) => answer === 0).length}
</p>
{renderResults()}
</div>
)}
</div>
Expand Down

0 comments on commit 6432e0a

Please sign in to comment.