Skip to content

Instantly share code, notes, and snippets.

@gilbarbara
Last active January 2, 2020 16:48
Show Gist options
  • Save gilbarbara/eff705243e96077a89ac6e5afc6bd778 to your computer and use it in GitHub Desktop.
Save gilbarbara/eff705243e96077a89ac6e5afc6bd778 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const { cancel } = actions;
const STATUS = {
IDLE: 'idle',
RUNNING: 'running',
READY: 'ready',
SUCCESS: 'success',
ERROR: 'error',
};
const getSuggestions = () =>
new Promise((resolve, reject) => {
setTimeout(() => {
// return reject(new Error('Failed to fetch'));
return resolve([
{ id: 1, title: 'Rua A, 1' },
{ id: 2, title: 'Rua B, 2' },
]);
}, 1000);
});
const getDetails = () =>
new Promise((resolve, reject) => {
setTimeout(() => {
// return reject(new Error('Failed to fetch'));
return resolve({ id: 1, title: 'Rua A, 1' });
}, 1000);
});
const addressSearch = Machine(
{
id: 'address-search',
initial: 'idle',
strict: true,
context: {
details: {},
detailsStatus: STATUS.IDLE,
error: '',
query: '',
suggestions: [],
suggestionsStatus: STATUS.IDLE,
visible: false,
},
on: {
RESET: {
target: 'idle',
actions: ['setValue'],
},
TYPE: 'typing',
},
states: {
idle: {},
typing: {
entry: ['setValue', 'startSuggestions'],
on: {
TYPE: {
actions: ['setValue', 'cancelSuggestions', 'startSuggestions'],
},
SEARCH: 'searching',
},
},
searching: {
invoke: {
src: getSuggestions,
onDone: {
target: 'list',
actions: assign({
error: '',
suggestions: (_, event) => event.data,
suggestionsStatus: STATUS.SUCCESS,
visible: true,
}),
},
onError: {
target: 'idle',
actions: assign({
error: (_, event) => event.data.toString(),
suggestionsStatus: STATUS.ERROR,
visible: false,
}),
},
},
},
list: {
on: {
DETAILS: 'details',
},
},
details: {
invoke: {
src: getDetails,
onDone: {
target: 'complete',
actions: assign({
details: (_, event) => event.data,
detailsStatus: STATUS.SUCCESS,
error: '',
visible: false,
}),
},
onError: {
target: 'list',
actions: assign({
error: (_, event) => event.data.toString(),
detailsStatus: STATUS.ERROR,
visible: false,
}),
},
},
},
complete: {
entry: 'reset'
}
},
},
{
actions: {
reset: assign({
error: '',
query: '',
suggestions: [],
suggestionsStatus: STATUS.IDLE,
visible: false,
}),
startSuggestions: send(
(_, evt) => {
if (evt.query && evt.query.length > 2) {
return { type: 'SEARCH', query: evt.query };
}
return { type: undefined };
},
{
delay: 400,
id: 'debounce',
},
),
cancelSuggestions: cancel('debounce'),
setValue: assign({
query: (_, evt) => {
// console.log('setValue', evt.query);
return evt.query || '';
},
}),
},
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment