Skip to content

Instantly share code, notes, and snippets.

@Glutnix
Last active March 6, 2020 00: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 Glutnix/f372e3732e2dd023a32988993685fb65 to your computer and use it in GitHub Desktop.
Save Glutnix/f372e3732e2dd023a32988993685fb65 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const searchStarWarsPeople = search =>
fetch(`https://swapi.co/api/people/?search=${search}`).then(response =>
response.json()
);
const searchMachine = Machine(
{
id: "searchMachine",
context: {
search: "",
result: {},
error: {}
},
initial: "blank",
states: {
blank: {
entry: "captureSearch"
},
debouncing: {
entry: "captureSearch",
after: {
300: "searching"
}
},
searching: {
invoke: {
id: "doSearch",
src: "fetchResults",
onDone: {
target: "searchSuccess",
actions: "captureResult"
},
onError: {
target: "searchFailure",
actions: "captureError"
}
}
},
searchSuccess: {
on: {
"": [
{
cond: "resultsEmpty",
target: "searchNoResults"
},
{
target: "searchResults"
}
]
}
},
searchResults: {},
searchNoResults: {},
searchFailure: {}
},
on: {
SEARCH_CHANGED: [
{
cond: "searchIsEmpty",
target: "blank"
},
{
target: "debouncing"
}
]
}
},
{
actions: {
captureSearch: assign((_ctx, evt) => {
return { search: evt.search };
}),
captureResult: assign({ result: (_ctx, evt) => evt.data }),
captureError: assign({ error: (_ctx, evt) => evt.data })
},
guards: {
searchIsEmpty: (_ctx, evt) => {
return !evt.search || evt.search.length === 0;
},
resultsEmpty: (ctx, _evt) => {
return ctx.result.count === 0;
}
},
services: {
fetchResults: (ctx, _evt) => searchStarWarsPeople(ctx.search)
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment