Skip to content

Instantly share code, notes, and snippets.

@cristiano-belloni
Last active March 20, 2021 03:39
Show Gist options
  • Save cristiano-belloni/be02f8904713cb8203a4e0baebdf627c to your computer and use it in GitHub Desktop.
Save cristiano-belloni/be02f8904713cb8203a4e0baebdf627c 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)
// We should move the defaults in (if possible, delays and guards), but only if this helps readability
// We should know how to get / override arguments (maxRetries, time??, see useQuery). Some are needed and some have a default
// We should allow cancellation?
// Maybe START / PAUSE / CANCEL events?
const fetchMachine = Machine({
id: 'backoff',
initial: 'init',
context: {
attempts: 0
},
states: {
init: {
on: {CONFIGURE: [
{ target: 'ready', cond: 'validateConf' },
{ target: 'failure' }
]},
entry: ['setConfiguration']
},
ready: { on: {
START: 'started',
}},
started: {
on: { '': [
{ target: 'requesting', cond: 'canRetry'},
{ target: 'failure' }
]}
},
requesting: {
invoke: {
id: 'fetch',
src: (context, event) => new Promise((_, reject) => reject("rejected")),
onDone: {
target: 'success',
actions: assign({ user: (context, event) => event.data })
},
onError: {
target: 'waiting',
actions: [assign({ error: (context, event) => event.data }),
assign({
attempts: (context, event) => context.attempts + 1
})
]
}
}
},
success: {
type: 'final'
},
failure: {
type: 'final'
},
waiting: {
after: {
DELAY: {
target: 'started',
}
}
}
}
}, {
delays: {
DELAY: (context, event) => {
return Math.min(1000 * 2 ** context.attempts, 30000);
},
},
guards: {
canRetry: (context, event) => {
return context.attempts < 3;
},
validateConf: (context, event) => !!event.promise //maybe??
},
actions: {
setConfiguration: assign({ promise: (_, event) => event.promise })
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment