Skip to content

Instantly share code, notes, and snippets.

@Jayphen
Last active February 14, 2020 13:47
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/40169716daa13a15f502b12d6dedfd2c to your computer and use it in GitHub Desktop.
Save Jayphen/40169716daa13a15f502b12d6dedfd2c 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)
// dynamically determine initial state
const initialPackageState = 'invalid'
const fetchMachine = Machine({
id: 'package',
initial: 'invalid',
context: {
retries: 0,
items: [{ valid: true }, { valid: true }]
},
states: {
invalid: {
on: {
VALIDATE: [{
target: 'valid',
cond: 'productsAreValid'
},
{ target: 'invalid' }
]
}
},
valid: {
on: {
FETCH_PRICE: 'fetching_price'
}
},
fetching_price: {
on: {
RESOLVE: 'buyable',
REJECT: 'error'
}
},
buyable: {
on: {
ADD_TO_CART: [{
target: 'added'
}, { target: 'failed' } ]
}
},
failed: {},
added: {
on: {
VALIDATE: [{
target: 'valid',
cond: 'productsAreValid'
},
{ target: 'invalid' }]
}
},
error: {
on: {
RETRY: {
target: 'fetching_price',
actions: assign({
retries: (context, event) => context.retries + 1
})
}
}
}
}
},
{ guards: { productsAreValid } }
);
function productsAreValid(context, event) {
const { items } = context;
if (!items) return false;
const length = items.length;
const validItems = items.filter(item => item.valid);
return length === validItems.length
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment