I am fetching data from an api.Trying to make quiz application from the data of an API.I have selected random countries and their respective capitals and map them to my quiz application.I have achieved this already.Now i am trying to shuffle my answer options but not able to do that.anybody can please help? Here is my code
JavaScript
x
177
177
1
import React from "react";
2
import "./Quiz.css";
3
import { useState, useEffect } from "react";
4
function Quiz() {
5
6
const [cname, scname] = useState([]);
7
const [results, finalres] = useState(false);
8
const [score, setScore] = useState(0);
9
const [currentQues, setCurrentQues] = useState(0);
10
//Get Method
11
useEffect(() => {
12
fetch("https://countriesnow.space/api/v0.1/countries/capital")
13
.then((response) => {
14
return response.json();
15
})
16
.then((data) => {
17
scname(data.data);
18
});
19
}, []);
20
// const questions=[{},[{}]];
21
// const questionText=Array.of(data.data.name)
22
23
// const answerOptions=[{}];
24
25
const restartGame = () => {
26
setScore(0);
27
setCurrentQues(0);
28
finalres(false);
29
30
31
};
32
let namearray = [5];
33
var capitalArray = [5];
34
35
let fx = (i) => {
36
let countryName = "";
37
let capitalName = "";
38
let countryNum = Math.floor(Math.random() * cname.length);
39
if (countryNum) {
40
countryName = cname[countryNum].name;
41
capitalName = cname[countryNum].capital;
42
43
}
44
namearray[i] = countryName;
45
capitalArray[i] = capitalName;
46
};
47
48
for (let i = 0; i < 5; i++) {
49
fx(i);
50
}
51
52
// console.log(capitalArray.length)
53
// function shuffle(array) {
54
// let currentIndex = array.length, randomIndex;
55
56
// // While there remain elements to shuffle.
57
// while (currentIndex != 0) {
58
59
// // Pick a remaining element.
60
// randomIndex = Math.floor(Math.random() * currentIndex);
61
// currentIndex--;
62
63
// // And swap it with the current element.
64
// [array[currentIndex], array[randomIndex]] = [
65
// array[randomIndex], array[currentIndex]];
66
// }
67
68
// return array;
69
70
// }
71
72
73
74
const questions = [
75
{
76
questionText: "What is the capital of " + namearray[0] + "?",
77
answerOptions: [
78
{ answerText: capitalArray[0], isCorrect: true },
79
{ answerText: capitalArray[1], isCorrect: false },
80
{ answerText: capitalArray[2], isCorrect: false },
81
{ answerText: capitalArray[3], isCorrect: false },
82
],
83
},
84
{
85
questionText: "What is the capital of " + namearray[1] + "?",
86
answerOptions: [
87
{ answerText: capitalArray[4], isCorrect: false },
88
{ answerText: capitalArray[1], isCorrect: true },
89
{ answerText: capitalArray[0], isCorrect: false },
90
{ answerText: capitalArray[3], isCorrect: false },
91
],
92
},
93
{
94
questionText: "What is the capital of " + namearray[2] + "?",
95
answerOptions: [
96
{ answerText: capitalArray[1], isCorrect: false },
97
{ answerText: capitalArray[0], isCorrect: false },
98
{ answerText: capitalArray[2], isCorrect: true },
99
{ answerText: capitalArray[3], isCorrect: false },
100
],
101
},
102
{
103
questionText: "What is the capital of " + namearray[3] + "?",
104
answerOptions: [
105
{ answerText: capitalArray[0], isCorrect: false },
106
{ answerText: capitalArray[2], isCorrect: false },
107
{ answerText: capitalArray[1], isCorrect: false },
108
{ answerText: capitalArray[3], isCorrect: true },
109
],
110
},
111
{
112
questionText: "What is the capital of " + namearray[4] + "?",
113
answerOptions: [
114
{ answerText: capitalArray[4], isCorrect: true },
115
{ answerText: capitalArray[1], isCorrect: false },
116
{ answerText: capitalArray[2], isCorrect: false },
117
{ answerText: capitalArray[3], isCorrect: false },
118
],
119
},
120
];
121
const hoc = (isCorrect) => {
122
if (isCorrect === true) {
123
setScore(score + 1);
124
}
125
const nextq = currentQues + 1;
126
if (nextq < questions.length) {
127
setCurrentQues(nextq);
128
} else {
129
finalres(true);
130
}
131
132
133
};
134
135
// const shuffle = () => 0.5 - Math.random();
136
137
// const testQuestions = questions.map(q => ({
138
// ...q,
139
// // this one shuffles the answers...
140
141
// answerOptions: q.answerOptions.sort(shuffle)
142
143
// })
144
// )
145
console.log('data')
146
return (
147
<>
148
<h4>Quiz</h4>
149
<div id="head">Welcome User</div>
150
<hr />
151
{results ? (
152
<div className="final-res">
153
Final Results
154
<h4>you scored {score} out of 5</h4>
155
<button onClick={() => restartGame()}>Restart</button>
156
</div>
157
) : (
158
<div>
159
<div id="quescard">
160
<h3>
161
{currentQues + 1}. {questions[currentQues].questionText}
162
</h3>
163
{questions[currentQues].answerOptions.map((ansopt) => (
164
165
<button onClick={() => hoc(ansopt.isCorrect)}>
166
{ansopt.answerText}
167
</button>
168
))}
169
</div>
170
</div>
171
)}
172
</>
173
);
174
}
175
176
export default Quiz
177
I have applied shuffle function but not sure whether its working or not
Advertisement
Answer
you can shuffle an array as so having a function in the component function body as below
JavaScript
1
9
1
const shuffledAnswers = (currentQues) => {
2
let shuffled = questions[currentQues].answerOptions
3
.map((value) => ({ value, sort: Math.random() }))
4
.sort((a, b) => a.sort - b.sort)
5
.map(({ value }) => value);
6
7
return shuffled;
8
};
9
and then in render you can invoke it as
JavaScript
1
6
1
{
2
shuffledAnswers(currentQues).map((ansopt) => (
3
<button onClick={() => hoc(ansopt.isCorrect)}>{ansopt.answerText}</button>
4
));
5
}
6
added the relevant code only to keep it simple … hope it works and is the expected result