I am trying to randomize questions option but ı cant actually also app rendering themself 4 times. how to solve? This is my first question on stackowerflow.
const [startPage,setStartPage]=React.useState(false)
const [questionsData,setQueationsData]=React.useState([])
React.useEffect(()=>{
fetch("https://opentdb.com/api.php?amount=1&type=multiple")
.then(res => res.json())
.then(data => (setQueationsData(data.results[0])))
},[1])
console.log(questionsData)
function question(){
//! I am trying top arrange randomly answer but not easy
const incorrect_answers=questionsData.incorrect_answers
console.log(incorrect_answers)
const correct_answer=questionsData.correct_answer
console.log(correct_answer)
const answer = incorrect_answers;
answer.splice(Math.floor(Math.random() * (incorrect_answers.length + 1)), 0,correct_answer);
console.log(answer)
return (<h3>{questionsData.question}</h3>)
return (answer.map(answer=>{ return ( <h2>{answer}</h2>)}))
}
What you can do is to have a separate function e.g. getAnswers() which will provide an array with shuffled values of all possible answers. In this functions you could have something like:
const getAnswers = () => {
let incorrectAnswers = questionsData.incorrect_answers
let correctAnswer = questionsData.correct_answer
let answers = [];
return answers = shuffle(incorrectAnswers.concat(correctAnswer)
}
Here you have a function which collects all possible answers in one array, pass this array into a shuffle() functions and then returns the answers in random order.
A possible shuffle() functions could be:
shuffle(array){
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
// Pick a random available number
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}