Skip to content

Instantly share code, notes, and snippets.

@Jayphen
Last active February 19, 2020 22:12
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/7ef7586255a1daa4641b703b79bb4008 to your computer and use it in GitHub Desktop.
Save Jayphen/7ef7586255a1daa4641b703b79bb4008 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)
function deriveStatus(items) {
return 'valid'
}
const fetchMachine = Machine(
{
id: 'package',
initial: 'validating',
context: { items: {}, price: 0, error: null },
on: {
UPDATE_ITEM: {
actions: 'updateItems',
target: 'validating'
}
},
states: {
invalid: {},
validating: {
on: {
'': [
{
target: 'valid',
cond: context => {
return deriveStatus(context.items) === 'valid';
}
},
{
target: 'invalid',
cond: context => {
return deriveStatus(context.items) !== 'valid';
}
}
]
}
},
valid: {
initial: 'fetchingPrice',
states: {
fetchingPrice: {
invoke: {
id: 'fetchPrice',
src: 'fetchPrice',
onDone: {
target: 'buyable',
actions: assign({ price: (_, event) => event.data })
},
onError: {
target: 'error',
actions: assign({ error: (_, event) => event.data })
}
}
},
buyable: {
on: {
ADD_TO_CART: 'added',
ERROR: 'error',
ADDED: 'added'
}
},
added: {
invoke: {
id: 'added-refetch',
src: () => {
return new Promise(resolve => {
setTimeout(() => {
resolve(400);
}, 800);
});
},
onDone: {
target: '#package.validating'
}
}
},
error: {}
}
}
}
},
{
actions: {
updateItems: assign({
items: (context, event) => {
if (event.type === 'UPDATE_ITEM') {
const { articleNumber, valid, variantArticleNumber } = event;
const items = produce(context.items, draft => {
draft[articleNumber] = {
...draft[articleNumber],
valid,
variantArticleNumber
};
});
return items;
}
}
})
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment