Last active
March 2, 2020 21:39
-
-
Save avanslaars/f9d4a18a8581d063a8decf5c84432245 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
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
const fetchMachine = Machine({ | |
id: 'fetch', | |
initial: 'idle', | |
context: { | |
retryCount: 0, | |
result: '' | |
}, | |
states: { | |
idle: { | |
on: { | |
FETCH: 'loading' | |
}, | |
}, | |
loading: { | |
invoke: { | |
src: 'loadData', | |
onDone: {target: 'success', actions: 'handleData'}, | |
onError: 'failure' | |
}, | |
}, | |
success: { | |
type: 'final' | |
}, | |
failure: { | |
on: { | |
'': [ | |
{ | |
target: 'awaitingRetry', | |
actions: 'incRetryCount', | |
cond: 'withinRetryLimit' | |
}, {target: 'terminated'} | |
] | |
} | |
}, | |
awaitingRetry: { | |
after: { | |
FETCH_DELAY: { | |
target: 'loading' | |
} | |
} | |
}, | |
terminated: { | |
type: 'final' | |
} | |
} | |
}, { | |
delays: { | |
FETCH_DELAY: (ctx) => ctx.retryCount * 500 | |
}, | |
guards: { | |
withinRetryLimit: ctx => ctx.retryCount < 5 | |
}, | |
actions: { | |
handleData: assign({result: (_, event) => event.data}), | |
incRetryCount: assign({ | |
retryCount: (context, event) => context.retryCount + 1 | |
}) | |
}, | |
services: { | |
loadData: (ctx, evt) => new Promise((res, rej) => { | |
setTimeout(() => { | |
ctx.retryCount > 6 ? res('win') : rej() | |
}, 500) | |
}) | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment