-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
83 lines (74 loc) · 2.29 KB
/
Copy pathApp.js
File metadata and controls
83 lines (74 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import React, { useState, useEffect, useRef } from 'react';
import FlashcardList from './FlashcardList';
import './App.css'
import axios from 'axios'
function App() {
const [flashcards, setFlashcards] = useState([])
const [categories, setCategories] = useState([])
const categoryEl = useRef()
const amountEl = useRef()
useEffect(() => {
axios
.get('https://opentdb.com/api_category.php')
.then(res => {
setCategories(res.data.trivia_categories)
})
}, [])
useEffect(() => {
}, [])
function decodeString(str) {
const textArea = document.createElement('textarea')
textArea.innerHTML= str
return textArea.value
}
function handleSubmit(e) {
e.preventDefault()
axios
.get('https://opentdb.com/api.php', {
params: {
amount: amountEl.current.value,
category: categoryEl.current.value
}
})
.then(res => {
setFlashcards(res.data.results.map((questionItem, index) => {
const answer = decodeString(questionItem.correct_answer)
const options = [
...questionItem.incorrect_answers.map(a => decodeString(a)),
answer
]
return {
id: `${index}-${Date.now()}`,
question: decodeString(questionItem.question),
answer: answer,
options: options.sort(() => Math.random() - .5)
}
}))
})
}
return (
<>
<form className="header" onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="category">Category</label>
<select id="category" ref={categoryEl}>
{categories.map(category => {
return <option value={category.id} key={category.id}>{category.name}</option>
})}
</select>
</div>
<div className="form-group">
<label htmlFor="amount">Number of Questions</label>
<input type="number" id="amount" min="1" step="1" defaultValue={10} ref={amountEl} />
</div>
<div className="form-group">
<button className="btn">Generate</button>
</div>
</form>
<div className="container">
<FlashcardList flashcards={flashcards} />
</div>
</>
);
}
export default App;