mardi 31 août 2021

randomize question and answers from an api async/await

I am creating a random questions quiz using opentdb api. I'm using async/await in js to try and grab a question at random from the database, display it, and display the answers at random in each button I made. Here is my code, any help would be great!

const answerBtn = document.querySelector(".answers")
const questionsDisplay = document.querySelector("#questions")
let shuffleQuestions, currentQuestion
async function fetchData(results) {
   try {
      let res = await axios.get(url)
      let choices = res.data
      console.log(choices)
      choices.results.forEach((result) => {
         console.log(result)
         questionSelect(result.question)
         getAnswer(result.correct_answer, result.incorrect_answers)
      })   
   } catch(error) {
      console.log(error)
   }
}
fetchData()

function questionSelect(results, question) {
   shuffleQuestions = [results].slice(question).sort(() => Math.random() - .5)
   currentQuestion = 0
   nextQuestion()
}

function nextQuestion() {
   questions(shuffleQuestions[currentQuestion])
}

function questions(question) {
   questionsDisplay.innerText = question
}

function getAnswer(correct_answer, incorrect_answers) {
   // Shuffle through answers and place them randomly
  incorrect_answers.forEach((incorrect_answer) => {
     Math.floor(Math.random() * 3) + 1
     answerBtn.append(incorrect_answer)
     if(correct_answer) {
        answerBtn.dataset.correct = correct_answer
     }
  })
}
<div class="questions-container">
  <h2 id="questions" class="questions" data-id="4">What is your favorite color?</h2>
</div>
<div class="buttons">
  <button id="a" class="answers" data-id="6">A</button>
  <button id="b" class="answers" data-id="7">B</button>
  <button id="c" class="answers" data-id="8">C</button>
  <button id="d" class="answers" data-id="9">D</button>
</div>



Aucun commentaire:

Enregistrer un commentaire