Skip to content

Instantly share code, notes, and snippets.

@gsong
Last active March 4, 2020 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsong/97a74f08b08824764db2db1d39435905 to your computer and use it in GitHub Desktop.
Save gsong/97a74f08b08824764db2db1d39435905 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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