Skip to content

Instantly share code, notes, and snippets.

@biesbjerg
Last active December 23, 2020 22:06
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 biesbjerg/d1884ab0b2a6b153249e7329ea6e4742 to your computer and use it in GitHub Desktop.
Save biesbjerg/d1884ab0b2a6b153249e7329ea6e4742 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const fetchMachine = Machine({
id: "searchMachine",
initial: "idle",
context: {
query: "hest",
results: null,
suggestions: null,
errorMessage: null
},
states: {
idle: {
on: {
SEARCH: {
target: "fetchingResults",
cond: "validQuery",
actions: ["reset"]
}
}
},
fetchingResults: {
invoke: {
id: 'fetchResults',
src: "fetchResults",
onDone: [
{
cond: "hasResults",
target: "showingResults"
},
{
cond: "hasNoResults",
target: "fetchingSuggestions"
}
],
onError: {
target: "searchFailure",
actions: assign({
errorMessage: "search error occurred"
})
}
}
},
showingResults: {
on: {
SEARCH: "fetchingResults"
}
},
fetchingSuggestions: {
invoke: {
id: 'fetchSuggestions',
src: "fetchSuggestions",
onDone: [
{
target: "showingSuggestions",
cond: "hasSuggestions"
},
{
target: "showingNoResults",
cond: "hasNoSuggestions"
}
],
onError: {
target: "searchFailure"
}
}
},
showingSuggestions: {
on: {
SEARCH: "fetchingResults"
}
},
showingNoResults: {
on: {
SEARCH: "fetchingResults"
}
},
searchFailure: {
on: {
SEARCH: "fetchingResults"
}
}
}
},
{
guards: {
hasResults: (context, event) => {
return context.results !== null;
},
hasNoResults: (context, event) => {
return context.results === null;
},
hasSuggestions: (context, event) => {
return context.suggestions !== null;
},
hasNoSuggestions: (context, event) => {
return context.suggestions === null;
},
validQuery: (context, event) => {
return context.query.length > 0;
}
},
actions: {
reset: (context, event) => {
context.results = null;
context.suggestions = null;
context.errorMessage = null;
},
fetchResults: async (context, event) => {
return Promise.resolve();
},
fetchSuggestions: async (context, event) => {
return Promise.resolve();
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment