Skip to content

Instantly share code, notes, and snippets.

@sesteva
Last active February 19, 2020 18:04
Show Gist options
  • Save sesteva/b58ca3ee62187b0dce83173d555ab726 to your computer and use it in GitHub Desktop.
Save sesteva/b58ca3ee62187b0dce83173d555ab726 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const results = [
{
"category":"Entertainment: Video Games",
"type":"multiple",
"difficulty":"easy",
"question":"Which game did "Sonic The Hedgehog" make his first appearance in?",
"correct_answer":"Rad Mobile",
"incorrect_answers":[
"Sonic The Hedgehog",
"Super Mario 64",
"Mega Man"
]
},
{
"category":"Science & Nature",
"type":"boolean",
"difficulty":"easy",
"question":"Igneous rocks are formed by excessive heat and pressure.",
"correct_answer":"False",
"incorrect_answers":[
"True"
]
},
{
"category":"General Knowledge",
"type":"multiple",
"difficulty":"easy",
"question":"Which company did Valve cooperate with in the creation of the Vive?",
"correct_answer":"HTC",
"incorrect_answers":[
"Oculus",
"Google",
"Razer"
]
}
]
function getQuestions(context) {
return new Promise((resolve, reject) => {
setTimeout( function() {
resolve(results)
}, 250)
})
// return fetch('/api/users/${context.userId}').then(response =>
// response.json()
// );
}
const incrementAnswers = assign({
answers: (context, event) => ({
...context.answers,
total:context.answers.total + 1
})
});
const quizMachine = Machine({
id: 'quiz',
initial: 'idle',
context: {
data: null,
answers: {
correct: 0,
incorrect: 0,
total: 0,
score: 0
}
},
states: {
idle: {
on: {
START: 'gettingQuestions'
}
},
gettingQuestions: {
invoke: {
src: getQuestions,
onDone: {
target: 'question',
actions: assign({
data: (context, event) => event.data
})
}
}
},
question: {
entry: 'incrementAnswers',
on: {
NEXT: [
{
target: 'summary',
cond: (context, event) => context.data.length === context.answers.total
},
{ target: 'question' }
]
}
},
summary: {
on:{
RESTART: 'question'
}
}
}
}, {
actions: {incrementAnswers}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment