Skip to content

Commit 95a3a1f

Browse files
committed
resolved fetching errors
1 parent 7a43c50 commit 95a3a1f

File tree

3 files changed

+45
-10
lines changed

3 files changed

+45
-10
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
/test.html
1+
/test.html
2+
game-old.js

game.js

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,37 @@ let questionCounter = 0
1414
let availableQuestions = {}
1515

1616
let questions = []
17+
let reloads = sessionStorage.getItem('reloads') ? parseInt(sessionStorage.getItem('reloads')) : 0
18+
19+
const fetchQuestions = () => {
20+
21+
const fetchTimeout = setTimeout(() => {
22+
if(reloads < 3){
23+
reloads++
24+
sessionStorage.setItem('reloads', reloads)
25+
window.location.reload()
26+
}else{
27+
console.error('Max reload attempts reached. Unable to fetch questions.')
28+
}
29+
}, 10000);
30+
31+
32+
1733
fetch("https://opentdb.com/api.php?amount=10&category=9&difficulty=easy&type=multiple")
1834
.then(res => {
35+
clearTimeout(fetchTimeout);
1936
return res.json()
2037
})
2138
.then(loadedQuestions => {
22-
console.log(loadedQuestions)
39+
// console.log(loadedQuestions)
40+
if(!loadedQuestions.results || loadedQuestions.results.length === 0){
41+
throw new Error("No Questions received")
42+
}
43+
44+
reloads = 0 // resetting to 0, if loadedQuestions received
45+
sessionStorage.setItem('reloads', reloads)
46+
47+
2348
questions = loadedQuestions.results.map(loadedQuestion => {
2449
const formattedQuestion = {
2550
question: loadedQuestion.question
@@ -39,16 +64,25 @@ fetch("https://opentdb.com/api.php?amount=10&category=9&difficulty=easy&type=mul
3964

4065
return formattedQuestion
4166
})
67+
68+
4269
startGame()
4370
}).catch(err => {
44-
()=> sessionStorage.clear()
45-
// Check if the page has already been reloaded
46-
if (!sessionStorage.getItem('reloaded')) {
71+
clearTimeout(fetchTimeout)
72+
console.error("Error fetching questions:", err)
73+
74+
if(reloads < 3){
75+
reloads++
76+
sessionStorage.setItem('reloads', reloads)
4777
window.location.reload()
48-
sessionStorage.setItem('reloaded', 'true');
49-
// //this flag is set as an indicator of reload
50-
}
51-
})
78+
} else{
79+
console.error("Max reload attempts reached. Unable to fetch questions.");
80+
}
81+
82+
});
83+
}
84+
85+
fetchQuestions()
5286

5387
//CONSTANTS
5488
const CORRECT_BONUS = 10

index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,6 @@ <h1>Quick Quiz</h1>
1515
<a class="btn" href="highScores.html">High Scores</a>
1616
</div>
1717
</div>
18-
<script src="game.js"></script>
18+
1919
</body>
2020
</html>

0 commit comments

Comments
 (0)