Skip to content

Instantly share code, notes, and snippets.

@remyoudemans
Last active April 27, 2021 16:32
Show Gist options
  • Save remyoudemans/e6f6348114171dd74d6ec38bacf15d1f to your computer and use it in GitHub Desktop.
Save remyoudemans/e6f6348114171dd74d6ec38bacf15d1f to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const singleData = context => {
return context.dataLength < 2;
};
const multipleData = context => {
return context.dataLength > 1;
};
const isEnough = context => !!context.enough;
const isSingleAndEnough = context => singleData(context) && isEnough(context);
const isSingleAndNotEnough = cx => singleData(cx) && !isEnough(cx);
const loopMachine = Machine(
{
id: 'loop',
initial: 'loopQuestions',
context: {
dataLength: 1,
enough: false,
currentSubmitted: false,
},
states: {
loopQuestions: {
on: {
SUBMIT: [
{
cond: multipleData,
target: 'summary',
actions: 'setCurrentSubmittedToTrue'
},
{
cond: isSingleAndEnough,
target: 'singleDone',
actions: 'setCurrentSubmittedToTrue'
},
{
cond: isSingleAndNotEnough,
target: 'summary',
actions: 'setCurrentSubmittedToTrue'
}
],
BACK: [
{
cond: multipleData,
target: 'summary',
// TODO: if adding, decrement dataLength (because they didn't finish adding)
actions: 'setCurrentSubmittedToTrue'
},
{
cond: singleData,
target: 'loopQuestions',
actions: 'exitBack'
},
],
},
},
summary: {
on: {
ADD: {
target: 'loopQuestions',
actions: [
'incrementDataLength',
'setCurrentSubmittedToFalse'
],
},
EDIT: {
target: 'loopQuestions',
},
DELETE: {
target: 'summary',
actions: 'decrementDataLength',
cond: multipleData,
},
BACK: [
{
cond: multipleData,
target: 'summary',
actions: 'exitBack',
},
{
cond: singleData,
target: 'loopQuestions'
}
]
}
},
singleDone: {},
},
},
{
actions: {
incrementDataLength: assign((context, event) => ({
...context,
dataLength: context.dataLength + 1,
})),
decrementDataLength: assign((context, event) => ({
...context,
dataLength: context.dataLength - 1,
})),
setCurrentSubmittedToTrue: assign((context) => ({
...context,
currentSubmitted: true,
})),
setCurrentSubmittedToFalse: assign((context) => ({
...context,
currentSubmitted: false,
})),
exitBack: () => {
// TODO
console.log('Exit back!');
}
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment