Last active
February 14, 2020 13:47
-
-
Save Jayphen/40169716daa13a15f502b12d6dedfd2c to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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