Skip to content

Instantly share code, notes, and snippets.

@mikaelkaron
Last active September 27, 2019 18:27
Show Gist options
  • Save mikaelkaron/d34cedec449604151526ff2b095a50aa to your computer and use it in GitHub Desktop.
Save mikaelkaron/d34cedec449604151526ff2b095a50aa 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 FormMachine = submit => Machine(
{
id: "form",
initial: "idle",
context: {
valid: false,
changed: new Date()
},
states: {
idle: {
entry: sendParent("IDLE"),
initial: "initial",
states: {
initial: {
on: {
"": [
{
target: "valid",
cond: "valid"
},
{
target: "invalid"
}
]
}
},
valid: {
entry: sendParent("VALID"),
on: {
SUBMIT: "#pending",
}
},
invalid: {
entry: sendParent("INVALID")
}
},
on: {
INPUT: {
target: ".initial",
actions: "input"
}
}
},
pending: {
id: "pending",
entry: [sendParent("PENDING"), "pending"],
invoke: {
src: "submit",
onDone: "success",
onError: {
target: "failure",
actions: "error"
}
},
after: {
TIMEOUT: {
target: "failure",
actions: "timeout"
}
}
},
success: {
type: "final"
},
failure: {
on: {
"": "idle"
}
}
}
},
{
actions: {
input: assign((_context, { type, ...event }) => ({
changed: true,
valid: false,
...event
})),
pending: assign({ error: undefined }),
error: assign({
error: (_context, event) => event.data.message
}),
timeout: assign({ error: "Timeout: No response from backend" })
},
guards: {
valid: ctx => ctx.valid
},
delays: {
TIMEOUT: 2000
},
services: {
submit
}
}
);
const f = FormMachine(ctx => console.log(ctx))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment