Skip to content

Instantly share code, notes, and snippets.

@LevelbossMike
Last active December 14, 2020 08:56
Show Gist options
  • Select an option

  • Save LevelbossMike/2bc7819df5b42deefd400f53049b891e to your computer and use it in GitHub Desktop.

Select an option

Save LevelbossMike/2bc7819df5b42deefd400f53049b891e 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)
function validate(formObject) {
return formObject.validate()
}
function submitForm(submitFn, formObject) {
// TODO: promisify this?
return submitFn(formObject);
}
const fetchMachine = Machine({
id: 'form',
initial: 'idle',
context: {
formObject: {
validate: () => {}
},
submitFn: () => {}
},
type: 'parallel',
states: {
behavior: {
initial: 'idle',
states: {
idle: {
on: {
// TODO: use guardMeta to check if we can submit, i.e. are we valid and are we changed?
SUBMIT: 'busy'
}
},
busy: {
invoke: {
src: () => submitForm(context.onSubmit, context.formObject),
onDone: 'success',
onError: 'error'
}
},
success: {
entry: 'handleSubmitSuccess'
},
error: {
entry: 'handleSubmitError'
}
}
},
change: {
initial: 'unchanged',
states: {
unchanged: {
entry: [send('VALIDATE')],
on: {
CHANGE: 'changed'
}
},
changed: {
entry: [send('VALIDATE')],
on: {
CHANGE: [
{ target: 'unchanged', cond: 'isPristine' },
]
}
}
}
},
validity: {
initial: 'unknown',
states: {
unknown: {
on: {
VALIDATE: 'validating'
}
},
validating: {
invoke: {
src: (context) => validate(context.formObject),
onDone: 'valid',
onError: 'invalid'
},
on: {
VALIDATE: 'validating'
}
},
valid: {
on: {
VALIDATE: 'validating'
}
},
invalid: {
on: {
VALIDATE: 'validating'
}
}
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment