Skip to content

Instantly share code, notes, and snippets.

@pafry7
Last active March 11, 2020 15:56
Show Gist options
  • Save pafry7/5ce0dd83fc1df698dc04c47f213c87c3 to your computer and use it in GitHub Desktop.
Save pafry7/5ce0dd83fc1df698dc04c47f213c87c3 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 countryCodeReg = /^[\+][0-9]{2,4}$/;
const phoneNumberReg = /^[0-9]{7,10}$/;
const mockFetch = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.9) resolve("data");
else reject("oopsy doopsy");
}, 1500);
});
}
const isAuthenticated = (context, event) => {
if (Math.random() < 0.4){
return true;
}
else return false;
}
const authMachine = Machine({
id: 'auth',
initial: 'idle',
context: {
user: undefined,
error: undefined
},
states: {
idle: {
on: {
'':[{target: 'has_jwt', cond:'isAuthenticated'},{target:'has_no_jwt'}]
}
},
'has_no_jwt':{
initial: 'idle',
'idle':{
on: {
POST_DATA:[{
target:'.countryCodeError',
cond: (_,e)=> !countryCodeReg.test(e.countryCode)
},
{target:'.phoneNumberError',
cond: (_,e) => !phoneNumberReg.test(e.phoneNumber)
},
{target: "has_jwt"}]
}
},
states:{
'idle':{},
'countryCodeError':{},
'phoneNumberError':{},
'fetchError': {},
}
},
'has_jwt':{
initial:'idle',
states: {
'idle':{}
}
},
'loggedIn':{type:'final'},
'needData':{}
}
},
{
guards:{
isAuthenticated
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment