Last active
March 4, 2020 16:25
-
-
Save gsong/97a74f08b08824764db2db1d39435905 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
const ALL = "All"; | |
const fetchMachine = Machine( | |
{ | |
id: "fetch", | |
initial: "loading", | |
context: { characters: [], filtered: [], genders: [], retries: 0 }, | |
states: { | |
loading: { | |
invoke: { | |
src: "getCharacters", | |
onDone: { target: "success", actions: "updateCharacters" }, | |
onError: { target: "failure" }, | |
}, | |
}, | |
success: { on: { FILTER: { actions: "filter" } } }, | |
failure: { | |
after: { 1000: { target: "loading", cond: "okToRetry" } }, | |
exit: "updateRetries", | |
}, | |
}, | |
}, | |
{ | |
actions: { | |
updateCharacters: assign({ | |
characters: (_, { data }) => data, | |
filtered: (_, { data }) => data, | |
genders: (_, { data }) => [ | |
ALL, | |
...[...new Set(data.map(c => c.gender))].sort(), | |
], | |
}), | |
updateRetries: assign({ retries: ({ retries }) => retries + 1 }), | |
filter: assign({ | |
filtered: ({ characters }, { genderOption }) => | |
genderOption === ALL | |
? characters | |
: characters.filter(c => c.gender === genderOption), | |
}), | |
}, | |
guards: { okToRetry: ({ retries }) => retries < 5 }, | |
services: { | |
getCharacters: async () => { | |
const characters = await (await fetch( | |
"https://ghibliapi.herokuapp.com/people", | |
)).json(); | |
return characters.sort((a, b) => (a.name < b.name ? -1 : 1)); | |
}, | |
}, | |
}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment