Last active
March 16, 2020 13:49
-
-
Save avanslaars/c0e05f5ebb932ee09ec948f4dc396982 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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