Skip to content

Instantly share code, notes, and snippets.

@sylvanaar
Last active September 3, 2020 21:31
Show Gist options
  • Save sylvanaar/70938e3cd9a42a6cd6ff2979c29aed1d to your computer and use it in GitHub Desktop.
Save sylvanaar/70938e3cd9a42a6cd6ff2979c29aed1d 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 network = Machine(
{
id: "network",
initial: "init",
context: {
retries: 0,
result: null,
connected: true,
},
states: {
init: {
on: {
START: [{ target: "active", cond: "isOnline" }, { target: "complete.failed", cond: "isOffline" }]
},
},
active: {
initial: "running",
on: {
RESOLVE: "complete.succeeded",
CANCEL: "complete.cancelled",
},
states: {
running: {
on: {
OFFLINE: {
target: "paused.waiting",
// actions: [
// assign({
// result: { name: "error", message: "" },
// }),
// ],
},
REJECT: {
target: "paused.failure",
actions: [
assign({
result: { name: "error", message: "failed" },
}),
],
},
},
},
paused: {
initial: "waiting",
states: {
failure: {
// handling failures
on: {
RETRY: {
target: "#network.active",
actions: assign({
retries: (context, event) => context.retries + 1,
}),
},
FAIL: {
target: "#network.complete.failed",
},
},
},
waiting: {
on: {
ONLINE: "#network.active.running",
},
},
},
},
},
},
complete: {
initial: "succeeded",
states: {
succeeded: {
type: "final",
},
failed: {
type: "final",
},
cancelled: {
type: "final",
},
},
},
},
},
{
guards: {
didError: (context, event) => {
// check if error
return context.result == "error";
},
didNotError: (context, event) => {
// check if error
return context.result !== "error";
},
isOnline: (context, event) => {
return context.connected;
},
isOffline: (context, event) => {
return !context.connected;
},
},
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment