Skip to content

Instantly share code, notes, and snippets.

@boertel
Last active June 3, 2020 21:39
Show Gist options
  • Save boertel/8525e8b503e0e1f5db4e4d443d984189 to your computer and use it in GitHub Desktop.
Save boertel/8525e8b503e0e1f5db4e4d443d984189 to your computer and use it in GitHub Desktop.
Machine to handle service request steps on the device
const serviceRequestMachine = Machine({
id: 'service-request',
initial: 'service',
context: {
hasTerms: false,
hasQuantity: true,
quantity: 1,
terms: false,
},
states: {
service: {
on: {
REQUEST: 'request',
}
},
request: {
on: {
'': [
{
target: 'quantity', cond: 'hasQuantity'
},
{
target: 'terms',
cond: 'hasTerms'
},
{
target: 'phone', cond: 'hasNoQuantityOrNoTerms'
},
]
}
},
quantity: {
on: {
NEXT: [
{ target: 'terms', cond: 'hasTerms' },
{ target: 'phone', cond: 'hasNoTerms' },
],
INCREASE: {
target: 'quantity',
actions: 'increaseQuantity',
cond: 'canIncreaseQuantity'
},
DECREASE: {
target: 'quantity',
actions: 'decreaseQuantity',
cond: 'canDecreaseQuantity'
}
},
},
terms: {
on: {
ACCEPT: {
target: 'phone',
actions: 'acceptTerms'
}
}
},
phone: {
on: {
SEND: 'confirmation'
}
},
confirmation: {
after: {
5000: 'success'
},
on: {
DONE: 'success'
}
},
success: {
type: 'final'
}
}
}, {
actions: {
increaseQuantity: assign({ quantity: ({ quantity }) => quantity + 1 }),
decreaseQuantity: assign({ quantity: ({ quantity }) => quantity - 1 }),
acceptTerms: assign({ terms: () => true })
},
guards: {
canDecreaseQuantity: ({ quantity }) => quantity > 1,
canIncreaseQuantity: ({ quantity }) => quantity <= 10,
hasQuantity: ({ hasQuantity }) => hasQuantity,
hasTerms: ({ hasTerms }) => hasTerms,
hasNoQuantityOrNoTerms: ({ hasTerms, hasQuantity }) => !hasQuantity && !hasTerms,
hasNoTerms: ({ hasTerms }) => !hasTerms,
didAcceptTerms: ({ terms }) => terms,
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment