Skip to content

Instantly share code, notes, and snippets.

@zaydek

zaydek/xstate.js

Created Sep 19, 2020
Embed
What would you like to do?
const booleanMachine = Machine({
id: "bool",
initial: "false",
states: {
false: {
on: {
TOGGLE: "true",
},
},
true: {
on: {
TOGGLE: "false",
},
},
},
})
const successFetchMachine = Machine({
id: "successFetch",
initial: "fetching",
states: {
fetching: {
invoke: {
id: "fetchHandler",
src: (ctx, e) => new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, 1e3)
}),
onDone: "success",
onError: "failure",
},
},
failure: {
on: {
REFETCH: "fetching"
},
},
success: {
type: "final",
},
}
})
const maybeSuccessFetchMachine = Machine({
id: "maybeSuccessFetch",
initial: "fetching",
states: {
fetching: {
invoke: {
id: "fetchHandler",
src: (ctx, e) => new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.5) {
reject()
} else {
resolve()
}
}, 1e3)
}),
onDone: "success",
onError: "failure",
},
},
failure: {
on: {
REFETCH: "fetching"
},
},
success: {
type: "final",
},
}
})
const naiveRefetchForeverMachine = Machine({
id: "naiveRefetchForever",
initial: "fetching",
states: {
fetching: {
invoke: {
id: "fetchHandler",
src: (ctx, e) => new Promise((resolve, reject) => {
setTimeout(() => {
reject()
}, 1e3)
}),
onDone: "success",
onError: "fetching",
},
},
success: {
type: "final",
},
},
})
const transientRefetchForeverMachine = Machine({
id: "transientRefetchForever",
initial: "fetching",
states: {
fetching: {
invoke: {
id: "fetchHandler",
src: (ctx, e) => new Promise((resolve, reject) => {
setTimeout(() => {
reject()
}, 1e3)
}),
onDone: "success",
onError: "failure",
},
},
failure: {
on: {
"": "fetching",
},
},
success: {
type: "final",
},
},
})
const delayedRefetchForeverMachine = Machine({
id: "delayedRefetchForever",
initial: "fetching",
states: {
fetching: {
invoke: {
id: "fetchHandler",
src: (ctx, e) => new Promise((resolve, reject) => {
setTimeout(() => {
reject()
}, 1e3)
}),
onDone: "success",
onError: "failure",
},
},
failure: {
after: {
1e3: "fetching",
},
},
success: {
type: "final",
},
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.