Created
April 27, 2021 15:11
-
-
Save natemoo-re/9b64c5f5d0ad0d65d45a168f484ba56a to your computer and use it in GitHub Desktop.
Yet-to-be-named Statechart DSL
This file contains 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 = createMachine((statechart, { goto, send, store }) => { | |
store.retries = 0; | |
return statechart` | |
main machine fetch { | |
initial state idle { | |
on:FETCH ${() => goto('loading')} | |
} | |
state loading { | |
@enter ${async () => { | |
if (store.error) store.error = undefined; | |
try { | |
const res = await fetch('https://pokeapi.co/api/v2/pokemon/ditto'); | |
const data = await res.json(); | |
send('RESOLVE', { data }); | |
} catch (e) { | |
const error = e.message || 'An unknown error occured'; | |
send('REJECT', { error }); | |
} | |
}} | |
on:RESOLVE ${({ data }) => { | |
store.data = data; | |
goto('success') | |
}} | |
on:REJECT ${({ error }) => { | |
store.error = error; | |
goto('failure') | |
}} | |
} | |
state failure { | |
on:RETRY ${() => { | |
store.retries++; | |
goto('loading'); | |
}} | |
} | |
final state success {} | |
} | |
` | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment