Skip to content

Instantly share code, notes, and snippets.

@alavkx
Created August 10, 2020 21:48
Show Gist options
  • Save alavkx/20b37676e27216396926afd3697d2578 to your computer and use it in GitHub Desktop.
Save alavkx/20b37676e27216396926afd3697d2578 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const fetchQuizData = () =>
fetch(
`https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean`,
).then(response => response.json())
const normalizeQuizData = (data) =>
data.reduce(
(acc, obj) => [
...acc,
{
category: obj.category,
question: obj.question,
correctAnswer: obj.correct_answer === 'True' ? true : false,
userAnswer: undefined,
correct: undefined,
},
],
[],
)
const fetchAndNormalizeQuizData = () =>
new Promise(async (resolve, reject) => {
try {
const data = await fetchQuizData()
resolve(normalizeQuizData(data.results))
} catch (error) {
reject(error)
}
})
const machine = Machine(
{
id: 'Machine',
initial: 'welcome',
context: {
currentQuestion: 0,
questions: [],
totalCorrectAnswers: 0,
},
states: {
welcome: {
on: {
START_QUIZ: 'loading',
},
},
loading: {
invoke: {
id: 'getQuizData',
src: 'fetchAndNormalizeQuizData',
onDone: {
target: 'quiz',
actions: assign({
questions: (_, event) => (event.data)
}),
},
onError: {
target: 'failure',
},
},
},
failure: {
on: {
RETRY: 'loading',
START_OVER: 'welcome',
},
},
quiz: {
on: {
'': {
target: 'results',
actions: [],
cond: 'allQuestionsAnswered',
},
ANSWER_FALSE: {
actions: ['answerFalse', 'nextQuestion']
},
ANSWER_TRUE: {
actions: ['answerTrue', 'nextQuestion']
},
},
},
results: {
on: {
PLAY_AGAIN: 'welcome',
},
exit: 'resetGame',
},
},
},
{
actions: {
resetGame: assign({
currentQuestion: 0,
currentQuestionDisplay: 1,
questions: [],
totalCorrectAnswers: 0,
}),
answerTrue: assign({
totalCorrectAnswers: ctx => ctx.questions[ctx.currentQuestion].correctAnswer ? ctx.totalCorrectAnswers + 1 : ctx.totalCorrectAnswers
}),
answerFalse: assign({
totalCorrectAnswers: ctx => ctx.questions[ctx.currentQuestion].correctAnswer ? ctx.totalCorrectAnswers : ctx.totalCorrectAnswers + 1
}),
nextQuestion: assign({
currentQuestion: ctx => ctx.currentQuestion + 1
})
},
guards: {
allQuestionsAnswered: ctx => ctx.currentQuestion === ctx.questions.length,
},
services: {
fetchAndNormalizeQuizData: () => fetchAndNormalizeQuizData()
}
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment