Skip to content

Instantly share code, notes, and snippets.

@devstojko
Last active February 8, 2020 01:27
Show Gist options
  • Save devstojko/9e326394e55a065774cfb038a6367503 to your computer and use it in GitHub Desktop.
Save devstojko/9e326394e55a065774cfb038a6367503 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 initialContext = {
origin: '12',
destination: '12',
date: '2020-03-02',
suggestions: '',
errors: {
origin: false,
destination: false
},
locations: []
}
const fetchUser = userId =>
fetch("https://api.myjson.com/bins/bkhvk").then(response => response.json());
const fetchLocations = userId =>
fetch("https://api.myjson.com/bins/bkhvk").then(response => response.json()).catch(() => new Error());
const formMachine = Machine({
id: 'formMachine',
initial: 'init',
context: initialContext,
states: {
init: {
on: {
FETCH_LOCATIONS: {target: 'loading'},
}
},
loading: {
invoke: {
id: 'fetchLocations',
src: (ctx, e) => {
return fetchLocations()
},
onDone: {
target: 'ready',
actions: assign({ locations: (ctx, e) => e.data})
},
onError: {
target: 'error'
}
}
},
error: {
on: {
RETRY: {
target: 'init'
}
}
},
ready: {
initial: 'idle',
states: {
idle: {
on: {
SELECT: {
actions: assign((ctx, e) => ({[e.name]: e.value})),
target: 'selected'
},
SWAP: {
actions: assign((ctx, e) => ({
origin: ctx.destination,
destination: ctx.origin,
suggestions: ''
}))
},
SUBMIT: {
target: 'submiting',
},
RESET: {
actions: assign(initialContext)
}
}
},
submiting: {
on: {
'': [
{
target: 'success',
cond: (ctx, e) => ctx.origin.length > 0 && ctx.destination.length > 0
},
{
target: 'error'
}
]
}
},
selected: {
entry: 'clearErrors',
on: {
'': [
{
target: 'loading',
cond: (ctx, e) => {
if (e.name === 'date') {
return false;
}
return ctx.origin.length > 0 && ctx.destination.length === 0 ||
ctx.origin.length === 0 && ctx.destination.length > 0
}
},
{
target: 'idle'
}
]
}
},
loading: {
entry: 'focus',
invoke: {
id: 'search',
src: (ctx, e) => {
console.log(`Fetch ${e.value}`)
return fetchUser()
},
onDone: {
target: 'idle',
actions: assign({ suggestions: (ctx, e) => e.data})
},
onError: {
target: 'error'
}
}
},
success: {
entry: 'submit',
on: {
SUBMITED: {
target: 'idle'
}
}
},
error: {
on: {
'': {
target: 'idle',
actions: assign((ctx, e) => ({
errors: {
origin: ctx.origin.length === 0,
destination: ctx.destination.length === 0
}
}))
}
}
},
}
}
}
},
{
actions: {
focus: (ctx, e) => {
const inputName = e.name === 'origin' ? 'destination' : 'origin';
console.log(`Focus ${inputName} input`)
},
clearErrors: assign((ctx, e) => ({
errors: {
...ctx.errors,
[e.name]: false
}
})),
submit: (ctx, e) => {
console.log('form submit', ctx, e)
respond('SUBMITED')
}
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment