Skip to content

Instantly share code, notes, and snippets.

@biesbjerg
Last active December 25, 2020 09:53
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/c4e80eca3d10c67a239fca3b50e29ddd to your computer and use it in GitHub Desktop.
Save biesbjerg/c4e80eca3d10c67a239fca3b50e29ddd to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const canSearch = (context, event) => {
return event.query && event.query.length > 0;
}
const fetchResults = async (context, event) => {
if (!context.query.length) {
throw new Error('No query specified');
}
return [
`${context.query} Result A`,
`${context.query} Result B`,
`${context.query} Result C`
];
}
const fetchSuggestions = async (context, event) => {
if (!context.query.length) {
throw new Error('No query specified');
}
return [
`${context.query} Suggestion A`,
`${context.query} Suggestion B`,
`${context.query} Suggestion C`
];
}
const fetchMachine = Machine({
id: "search",
initial: "idle",
context: {
query: "",
results: null,
suggestions: null
},
states: {
idle: {
on: {
SEARCH: {
target: "fetchingResults",
cond: canSearch,
actions: [
"assignQuery",
"clearResults",
"clearSuggestions"
]
}
}
},
fetchingResults: {
invoke: {
id: 'fetchResults',
src: fetchResults,
onDone: [
{
target: "fetchingSuggestions",
cond: "hasNoResults"
},
{
target: "showingResults",
actions: "assignResults"
}
],
onError: {
target: "searchFailure"
}
}
},
showingResults: {
on: {
SEARCH: "fetchingResults"
}
},
showingResultsNotFound: {
on: {
SEARCH: "fetchingResults"
}
},
fetchingSuggestions: {
invoke: {
id: 'fetchSuggestions',
src: fetchSuggestions,
onDone: [
{
target: "showingResultsNotFound",
cond: "hasNoSuggestions"
},
{
target: "showingSuggestions",
actions: "assignSuggestions"
}
],
onError: {
target: "searchFailure"
}
}
},
showingSuggestions: {
on: {
SEARCH: "fetchingResults"
}
},
searchFailure: {
on: {
SEARCH: "fetchingResults"
}
}
}
},
{
guards: {
hasNoResults: (context, event) => {
return !!event.data;
},
hasNoSuggestions: (context, event) => {
return !!event.suggestions;
}
},
actions: {
assignQuery: assign({
query: (context, event) => event.query
}),
assignResults: assign({
results: (context, event) => event.data
}),
assignSuggestions: assign({
suggestions: (context, event) => event.data
}),
clearResults: (context, event) => {
context.results = null;
},
clearSuggestions: (context, event) => {
context.suggestions = null;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment