Skip to content

Instantly share code, notes, and snippets.

@seeden

seeden/machine.js

Created Feb 18, 2021
Embed
What would you like to do?
Generated by XState Viz: https://xstate.js.org/viz
const questionStates = {
initial: 'ready',
context: {
userAnswer: undefined,
oponentAnswer: undefined,
},
states: {
ready: {
on: {
ANSWER: 'wait_for_oponent_answer',
OPONENT_ANSWER: 'wait_for_user_answer',
},
},
wait_for_user_answer: {
on: {
ANSWER: 'results',
},
},
wait_for_oponent_answer: {
on: {
OPONENT_ANSWER: 'results',
},
},
results: {
exit: 'resetQuestion',
},
},
actions: {
resetQuestion: () => ({
userAnswer: undefined,
oponentAnswer: undefined,
}),
},
};
const quizStates = {
initial: 'quiz',
context: {
answers: [],
currentQuestion: 0,
currentQuestionDisplay: 1,
questions: [],
totalCorrectAnswers: 0,
},
states: {
quiz: {
on: {
NEXT_QUESTION: {
actions: ['nextQuestion']
},
},
...questionStates,
},
results: {
exit: 'resetQuiz',
},
},
actions: {
resetQuiz: () => ({
currentQuestion: 0,
currentQuestionDisplay: 1,
questions: [],
totalCorrectAnswers: 0,
}),
nextQuestion: (context) => ({
...context,
currentQuestion: context.currentQuestion + 1,
}),
},
};
const fetchMachine = Machine({
id: 'duel',
initial: 'welcome',
states: {
welcome: {
on: {
SEARCH: 'searching_oponent',
},
},
searching_oponent: {
on: {
OPONENT_FIND: 'quiz',
},
},
quiz: {
...quizStates,
},
results: {
on: {
PLAY_AGAIN: 'welcome',
},
exit: 'resetGame',
},
failure: {
on: {
RETRY: 'quiz',
START_OVER: 'welcome',
},
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment