Created
January 5, 2022 10:07
-
-
Save Conrad777/68c9f1004a3f98987ace963b7b839bb8 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) | |
function getInputMachine(id) { | |
const changeEventName = `CHANGE_${id.toUpperCase()}` | |
function validator(ctx, e) { | |
return e.text && e.text.length > 4 | |
} | |
function isValid(ctx, e) { | |
console.log('isValid', validator(ctx, e)) | |
return validator(ctx, e); | |
} | |
function isInvalid(ctx, e) { | |
console.log('isInvalid', !validator(ctx, e)) | |
return !validator(ctx, e); | |
} | |
const inputStateMachine = { | |
id, | |
initial: 'Valid', | |
context: { | |
text: 'abc' | |
}, | |
states: { | |
// state names of parallel machines can | |
// be namespaced with the higher level | |
// name given to the machine. E.g. username.Active and password.active are different. But the event names are same for all the machines inside the big machine. That is why had to create unique event names for each machine which are created using the constructor function | |
Valid: { | |
on: { | |
[changeEventName]: { | |
target: 'CheckValidity', | |
actions: [(ctx, e) => ctx[`${id}_text`] = e.text] | |
} | |
} | |
}, | |
CheckValidity: { | |
on: { | |
"": [ | |
{ | |
target: 'Valid', | |
cond: isValid, | |
}, | |
{ | |
target: 'Invalid', | |
cond: isInvalid, | |
} | |
] | |
} | |
}, | |
Invalid: { | |
on: { | |
[changeEventName]: { | |
target: 'CheckValidity', | |
actions: [(ctx, e) => ctx[`${id}_text`] = e.text] | |
} | |
} | |
}, | |
} | |
} | |
return inputStateMachine | |
} | |
const fetchMachine = Machine({ | |
id: 'login', | |
type: 'parallel', | |
// initial: 'Start', | |
context: { | |
}, | |
states: { | |
input: { | |
on: { | |
"SUBMIT": { | |
actions: [(context) => console.log('submitting user credentials', context)] | |
} | |
} | |
}, | |
username: { | |
...getInputMachine('username') | |
}, | |
password: { | |
...getInputMachine('password') | |
} | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment