Skip to content

Instantly share code, notes, and snippets.

@pafry7
Last active March 17, 2020 14:31
Show Gist options
  • Save pafry7/d13ad3cda8fcd9368df17d3090f68687 to your computer and use it in GitHub Desktop.
Save pafry7/d13ad3cda8fcd9368df17d3090f68687 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 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