Last active
March 17, 2020 14:31
-
-
Save pafry7/d13ad3cda8fcd9368df17d3090f68687 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
const phoneRegex = /^[0-9]{7,9}$/; | |
const countryCodeRegex = /^\+[0-9]{2,3}$/; | |
const initialContext = { | |
countryCode:"", | |
phoneNumber:"" | |
} | |
function mockFetch() { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (Math.random() < 0.8) resolve("got jwt"); | |
else reject("oopsy doopsy"); | |
}, 1500); | |
}); | |
} | |
const phoneNumber = Machine({ | |
id: 'phoneForm', | |
context: initialContext, | |
initial: 'idle', | |
states: { | |
idle: { | |
initial:'noErrors', | |
on:{ | |
"SEND":[ | |
{ | |
target:".invalidCountryCode", | |
cond:(_,e)=> !countryCodeRegex.test(e.countryCode) | |
}, | |
{ | |
target: ".invalidPhoneNumber", | |
cond: (_, e) => !phoneRegex.test(e.phoneNumber) | |
}, | |
{ | |
target:"loading", | |
actions:assign({ | |
countryCode: (_, e) => e.countryCode, | |
phoneNumber: (_, e) => e.phoneNumber | |
}) | |
} | |
] | |
}, | |
states:{ | |
noErrors:{}, | |
invalidCountryCode:{}, | |
invalidPhoneNumber:{}, | |
} | |
}, | |
loading:{ | |
invoke:{ | |
id:"sendPhoneNumber", | |
src: () => mockFetch(), | |
onDone:{ | |
target:"success" | |
}, | |
onError:{ | |
target:"failure" | |
} | |
} | |
}, | |
success: {type: 'final' }, | |
failure: { | |
on:{ | |
"RETRY":{ | |
target:"loading" | |
} | |
} | |
}, | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment