Home > Software engineering >  Displaying Quiz Answers
Displaying Quiz Answers

Time:02-10

I'm making a quizz project for my portfolio with reactJs, i fetch data from this link https://opentdb.com/api.php?amount=10&category=23&difficulty=medium after i fetch data, with my useState i set my quiz state to the given array of 10 questions, after that in rendering i iterate over this array i change indexes of question by handleClick function and so its easy for me to move on with questions but my mistake which im trying to solve for fourth day already(im a beginner) is that there is a given array of incorrect answers and it contains 3 incorrect answers and then there is a seperate string of correct answer, so my problem here is that i try to mix up incorrect and correct answers together and then map them and change the indexes but unfortunately i dont do it right and dont understand how to do it either can anyone explain?

import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState()
  const [answer,setAnswer] = useState([])
  const [correct,setCorrect] =useState('')
  const [points,setPoints] = useState(0)
  const [turns,setTurns] = useState(0)
  const [disabled,setDisabled] = useState(false)
  const [loading,setLoading] = useState(false)
  const [index,setIndex] = useState(0)
  const [res,setRes] = useState([])

  function refreshPage() {
    window.location.reload(false);
  }


 useEffect(() => {
  axios.get('https://opentdb.com/api.php?amount=10&category=23&difficulty=medium')
  .then(res =>{
    setRes(res)
    console.log(res.data)
    setQuiz(res.data.results)
    let tempVar = res.data.results[index]
    setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
    console.log(answer)

  
  })

  .catch(err=>{
    console.log(err)
  })

 }, []);
 
 const handleClick = (e) => {
  setIndex(index    1)
  setPoints(points   1)
  setTurns(turns   1)
  if(e.target.innerText === quiz[index].correct_answer){
    console.log('match')
  
  } else {
    console.log('not a match')
  }
 

 }
 
 if(points >= 10|| turns >=10){
   return (
     <div><h1>Well done</h1>
     <p>your score : {points}</p>
     </div>
   )
   }
 
  return (
  
    <div className="App">
<h1>{quiz && quiz[index].question}</h1>
{quiz &&  answer.map(answers => 
   <button key={answers} onClick={handleClick} >{answers}</button>
)}

    </div>

  );
}

export default App;

CodePudding user response:

  •  Tags:  
  • Related