Skip to content

Instantly share code, notes, and snippets.

@barucAlmaguer
Last active November 25, 2020 01:43
Show Gist options
  • Save barucAlmaguer/16a75f30e9e05656048637ece4e2e8a5 to your computer and use it in GitHub Desktop.
Save barucAlmaguer/16a75f30e9e05656048637ece4e2e8a5 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const triviaMachine = Machine({
id: 'trivia',
initial: 'home',
context: {
questions: [],
answers: [],
currentQuestion: 0,
totalQuestions: 10
},
states: {
home: {
on: {
START: 'loading_quiz'
}
},
loading_quiz: {
on: {
FULFILLED: {
target: 'quiz',
actions: 'saveQuizInfo'
},
REJECTED: {
target: 'error',
actions: 'showError'
}
}
},
quiz: {
on: {
// may also be written as quiz {always {...} }
'': {
target: 'results',
cond: 'quizFinished'
},
BACK: {
cond: 'notFirstQuestion',
target: 'quiz',
actions: 'goPrevQuestion'
},
FORWARD: {
cond: 'notLastQuestion',
target: 'quiz',
actions: 'goNextQuestion'
},
SUBMIT_ANSWER: {
target: 'quiz',
actions: ['saveAnswer', 'goNextQuestion']
}
}
},
results: {
on: {
BACK: 'home'
}
},
error: {
on: {
BACK: 'home'
}
}
}
}, {
guards: {
notFirstQuestion: (ctx) => ctx.currentQuestion > 0,
notLastQuestion: (ctx) => (
ctx.currentQuestion < ctx.totalQuestions - 1
),
quizNotFinished: (ctx) => (
ctx.answers.length === ctx.totalQuestions
),
},
actions: {
goPrevQuestion: assign({
currentQuestion: (ctx) => ctx.currentQuestion - 1
}),
goNextQuestion: assign({
currentQuestion: (ctx) => ctx.currentQuestion + 1
}),
saveAnswer: assign({
answers: (ctx, evt) => {
let newAnswers = [...ctx.answers]
newAnswers[ctx.currentQuestion] = evt.answer
return newAnswers
}
})
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment