Skip to content

Instantly share code, notes, and snippets.

@pafry7
Created March 17, 2020 14:39
Show Gist options
  • Save pafry7/62d20d9ef7eb8fdd326ce824bfc208ee to your computer and use it in GitHub Desktop.
Save pafry7/62d20d9ef7eb8fdd326ce824bfc208ee 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 codeRegex = /^[0-9]{6}$/;
const initialContext = {
code:""
}
function mockFetch() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.8) resolve("got jwt");
else reject("oopsy doopsy");
}, 1500);
});
}
const verificationCode = Machine({
id: 'verificationCodeForm',
context: initialContext,
initial: 'idle',
states: {
idle: {
initial:'noErrors',
on:{
"SEND":[
{
target:".invalidCode",
cond:(_,e)=> !codeRegex.test(e.code)
},
{
target:"loading",
actions:assign({
code: (_, e) => e.code,
})
}
],
"SEND_CODE_AGAIN":{target:".noErrors"}
},
states:{
noErrors:{},
invalidCode:{},
}
},
loading:{
invoke:{
id:"sendCode",
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