Skip to content

Instantly share code, notes, and snippets.

@Jayphen
Created February 13, 2020 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jayphen/5587e7318166724b71fb54c0e692f80f to your computer and use it in GitHub Desktop.
Save Jayphen/5587e7318166724b71fb54c0e692f80f 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)
const product = {
variants: {
values: [
{
articleNumber: 'blah'
},
{
articleNumber: 'two'
}]
}
}
const selectedVariant = null
const fetchMachine = Machine({
id: 'variant',
initial: 'unknown',
context: {product, selectedVariant},
states: {
unknown: {
on: {
'': [
{target: 'valid', cond: hasOneValue},
{target: 'invalid.incomplete'}
]
}
},
invalid: {
initial: 'incomplete',
on: {SELECTION: {
target: 'validating',
actions: assign({
selectedVariant: (context, event) => event.selectedVariant
})
}},
states: {
outOfStock: {},
incomplete: {}
}
},
validating: {
on: {
'': [
{ target: 'valid', cond: variantIsValid },
{ target: 'invalid.outOfStock', cond: variantIsOOS },
{ target: 'invalid.incomplete' }
]
}
},
valid: {}
}
});
function hasOneValue(ctx) {
return ctx.product.variants.values.length === 1
}
function variantIsValid(ctx) {
console.log(ctx)
return ctx.selectedVariant && ctx.selectedVariant.stockStatus.buyable
}
function variantIsOOS(ctx) {
return ctx.selectedVariant && !ctx.selectedVariant.stockStatus.buyable
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment