Skip to content

Instantly share code, notes, and snippets.

@pagameba
Created September 22, 2020 12:56
Show Gist options
  • Save pagameba/de067240d6bad504ea0b9e3f4c7940da to your computer and use it in GitHub Desktop.
Save pagameba/de067240d6bad504ea0b9e3f4c7940da 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 getCode = (email) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (email !== '[email protected]') {
reject({ code: 3 })
}
resolve()
}, 1000)
})
}
const emailStates = {
initial: 'noError',
states: {
noError: {
on: {
INPUT: [
{
cond: 'isEmailEmpty',
target: 'error.empty'
},
{
cond: 'isEmailBadFormat',
target: 'error.badFormat'
},
{
target: 'noError'
}
],
}
},
error: {
initial: 'empty',
states: {
empty: {},
badFormat: {},
noAccount: {},
},
},
}
}
const authServiceStates = {
initial: 'idle',
states: {
idle: {},
processing: {},
},
}
const loginMachine = Machine({
id: 'login',
initial: 'ready',
context: {
email: '[email protected]'
},
states: {
ready: {
type: 'parallel',
on: {
SUBMIT: [
{
cond: 'isEmailEmpty',
target: 'ready.email.error.empty'
},
{
cond: 'isEmailBadFormat',
target: 'ready.email.error.badFormat'
},
{
target: 'awaitingResponse',
}
]
},
states: {
email: { ... emailStates },
authService: { ...authServiceStates },
}
},
awaitingResponse: {
on: {
CANCEL: 'ready'
},
invoke: {
src: 'requestCode',
onDone: {
action: 'onSuccess'
},
onError: [
{
cond: 'isNoAccount',
target: 'ready.email.error.noAccount'
}
],
}
},
}
}, {
services: {
requestCode: (context, evt) => getCode(context.email)
},
guards: {
isEmailEmpty: (context, evt) => context.email === '',
isEmailBadFormat: (context, evt) => context.email === 'badFormat',
isNoAccount: (context, evt) => {
console.log('isNoAccount', evt)
if (evt.data) {
return evt.data.code === 3
} else {
return true
}
}
},
actions: {
cacheEmail: (context, evt) => ({
email: event.email
}),
onSuccess: (c, e) => {
alert('code!')
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment