Skip to content

Instantly share code, notes, and snippets.

@junhuif
Last active December 20, 2019 13:34
Show Gist options
  • Save junhuif/7d0827b7b170a6458d10ed2b36adcebe to your computer and use it in GitHub Desktop.
Save junhuif/7d0827b7b170a6458d10ed2b36adcebe to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const submitMachine = Machine(
{
initial: "idle",
context: {
orderCode: "some"
},
states: {
idle: {
on: {
SUBMIT: [
{ target: "updating", cond: "orderIsCreated" },
{ target: "creating" }
]
}
},
creating: {
invoke: {
id: "create-order",
src: "invokeCreateOrder",
onDone: "created",
onError: "create_failed"
}
},
create_failed: {
on: {
RETRY: "creating"
}
},
created: {
on: {
SUBMIT: "updating"
}
},
updating: {
invoke: {
id: "update-order",
src: "invokeUpdateOrder",
onDone: "updated",
onError: "update_failed"
}
},
update_failed: {
on: {
RETRY: "updating"
}
},
updated: {
on: {
SUBMIT: "updating"
}
}
}
},
{
guards: {
orderIsCreated: context => context.orderCode !== undefined
},
services: {
invokeCreateOrder: () =>
new Promise((resolve, reject) =>
setTimeout(() => {
Math.floor(Math.random() * 10) % 2 === 0
? resolve({
orderCode: String(Math.floor(Math.random() * 10000))
})
: reject("fail to create order");
}, 500)
),
invokeUpdateOrder: () =>
new Promise((resolve, reject) =>
setTimeout(() => {
Math.floor(Math.random() * 10) % 2 === 0
? resolve()
: reject("fail to update order");
}, 500)
)
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment