Skip to content

Instantly share code, notes, and snippets.

@cristiano-belloni
Last active March 20, 2021 03:39
Show Gist options
  • Select an option

  • Save cristiano-belloni/be02f8904713cb8203a4e0baebdf627c to your computer and use it in GitHub Desktop.

Select an option

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 remove resolve / reject and just pass a Promise as argument
// We should have a real exponential backoff algo
// We should allow cancellation?
// Maybe START / PAUSE events?
const fetchMachine = Machine({
id: 'linear_backoff',
initial: 'idle',
context: {
attempts: 0
},
states: {
idle: {
on: { '': [
{ target: 'loading', cond: 'canRetry'},
{ target: 'failure' }
]}
},
loading: {
invoke: {
id: 'getUser',
src: (context, event) => new Promise((_, reject) => reject("rejected")),
onDone: {
target: 'success',
actions: assign({ user: (context, event) => event.data })
},
onError: {
target: 'wait',
actions: [assign({ error: (context, event) => event.data }),
assign({
attempts: (context, event) => context.attempts + 1
})
]
}
}
},
success: {
type: 'final'
},
failure: {
type: 'final'
},
wait: {
after: {
LINEAR_DELAY: {
target: 'idle',
}
}
}
}
}, {
delays: {
LINEAR_DELAY: (context, event) => {
return (context.attempts + 1) * 500;
},
},
guards: {
canRetry: (context, event) => {
return context.attempts < 5;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment