Skip to content

Instantly share code, notes, and snippets.

@vin-e
Last active July 24, 2020 03:57
Show Gist options
  • Save vin-e/fd03464fbd6e7a188d3d7d8987b94d26 to your computer and use it in GitHub Desktop.
Save vin-e/fd03464fbd6e7a188d3d7d8987b94d26 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const validate = ({ value, validator }) => {
if (validator === undefined) {
return new Promise((resolve) => resolve())
}
return validator.validate(value)
}
const inputMachine = Machine({
id: 'input',
initial: 'valid',
context: {
errorMessage: undefined,
validator: undefined,
value: undefined
},
states: {
valid: {
on: {
INPUT_CHANGED: {
actions: 'updateValue'
}
}
},
validateContext: {
invoke: {
src: validate,
onDone: {
target: 'valid',
actions: 'clearError'
},
onError: {
target: 'error',
actions: 'setError'
}
}
},
error: {
on: {
CLEAR_ERROR: {
target: 'valid'
},
INPUT_CHANGED: {
target: 'validateContext',
actions: 'updateValue'
}
}
}
},
on: {
BLUR: 'validateContext'
}
}, {
actions: {
clearError: assign({
errorMessage: (_) => undefined
}),
setError: assign({
errorMessage: (_, event) => event.data.errors.join(' ')
}),
updateValue: assign((_, event) => ({
value: event.value
}))
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment