Skip to content

Instantly share code, notes, and snippets.

@avanslaars
Last active March 16, 2020 13:49
Show Gist options
  • Save avanslaars/c0e05f5ebb932ee09ec948f4dc396982 to your computer and use it in GitHub Desktop.
Save avanslaars/c0e05f5ebb932ee09ec948f4dc396982 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Fetch with retry and cancel
const fetchMachine = Machine({
id: 'fetch',
initial: 'idle',
context: {
results: [],
retries: 0,
},
states: {
idle: {
on: {
FETCH: 'loading',
},
},
loading: {
invoke: {
src: 'loadData',
onDone: { target: 'success', actions: 'handleData' },
onError: 'failure',
},
on: {
CANCEL: 'idle'
}
},
success: {},
terminated: {},
awaitingRetry: {
after: {
FETCH_DELAY: 'loading',
},
},
failure: {
on: {
'': [
{
target: 'awaitingRetry',
actions: 'increment',
cond: 'withinLimit',
},
{ target: 'terminated' },
],
// FETCH: { target: 'loading', actions: 'increment' },
},
},
},
},
{
services: {
loadData: () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('BOOM')
}, 2000)
})
}
},
actions: {
handleData: assign({ results: (_, event) => console.log('handling data') || event.data }),
increment: assign({ retries: context => context.retries + 1 }),
},
delays: {
FETCH_DELAY: context => context.retries * 500,
},
guards: {
withinLimit: (context) => context.retries < 4
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment