Skip to content

Instantly share code, notes, and snippets.

@rofrol
Last active February 11, 2021 14:34
Show Gist options
  • Save rofrol/08278952e023fa19e392cbb784002d1b to your computer and use it in GitHub Desktop.
Save rofrol/08278952e023fa19e392cbb784002d1b to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const machine = Machine(
{
id: 'Machine',
initial: 'welcome',
context: {
currentQuestion: 0,
currentQuestionDisplay: 1,
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: 'updateAnswer',
},
ANSWER_TRUE: {
actions: 'updateAnswer',
},
},
},
results: {
on: {
PLAY_AGAIN: 'welcome',
},
exit: 'resetGame',
},
},
},
{
actions: {
resetGame: assign({
currentQuestion: 0,
currentQuestionDisplay: 1,
questions: [],
totalCorrectAnswers: 0,
}),
updateAnswer: assign((ctx, event) => ({
questions: [
...ctx.questions.slice(0, ctx.currentQuestion),
{
...ctx.questions[ctx.currentQuestion],
userAnswer: event.answer,
correct:
ctx.questions[ctx.currentQuestion].correctAnswer === event.answer,
},
...ctx.questions.slice(ctx.currentQuestion + 1),
],
totalCorrectAnswers:
ctx.questions[ctx.currentQuestion].correctAnswer === event.answer
? (ctx.totalCorrectAnswers += 1)
: ctx.totalCorrectAnswers,
currentQuestion: ctx.currentQuestion += 1,
currentQuestionDisplay: ctx.currentQuestionDisplay += 1,
})),
},
guards: {
allQuestionsAnswered: ctx => {
return (
ctx.questions.filter(
(question) => question.correct !== undefined,
).length === ctx.questions.length && true
)
},
},
services: {
fetchAndNormalizeQuizData: () => fetchAndNormalizeQuizData(),
},
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment