Last active
March 3, 2020 20:17
-
-
Save avanslaars/2e4edd86ae71c4c7cf23719b1cb67c9e to your computer and use it in GitHub Desktop.
fetch machine including retry with backoff logic - 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
const fetchMachine = Machine( | |
{ | |
id: 'fetch', | |
initial: 'idle', | |
context: { | |
results: [], | |
retryCount: 0, | |
}, | |
states: { | |
idle: { | |
on: { | |
FETCH: 'loading', | |
}, | |
}, | |
loading: { | |
invoke: { | |
src: 'loadData', | |
onDone: { target: 'success', actions: 'handleData' }, | |
onError: { target: 'failure' }, | |
}, | |
on: { | |
RESOLVE: 'success', | |
REJECT: 'failure', | |
}, | |
}, | |
success: {}, | |
failure: { | |
on: { | |
'': [ | |
{ | |
target: 'awaitingRetry', | |
actions: 'incRetry', | |
cond: 'withinLimit', | |
}, | |
{ target: 'terminated' }, | |
], | |
}, | |
}, | |
awaitingRetry: { | |
after: { | |
FETCH_DELAY: 'loading', | |
}, | |
}, | |
terminated: {}, | |
}, | |
}, | |
{ | |
services: { | |
loadData: (ctx, evt) => new Promise((res, rej) => { | |
setTimeout(() => { | |
ctx.retryCount > 6 ? res('win') : rej() | |
}, 500) | |
}) | |
}, | |
guards: { | |
withinLimit: context => context.retryCount < 5, | |
}, | |
actions: { | |
handleData: assign({ results: (_, event) => event.data }), | |
incRetry: assign({ retryCount: context => context.retryCount + 1 }), | |
}, | |
delays: { | |
FETCH_DELAY: (context, event) => context.retryCount * 500, | |
}, | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment