Last active
July 24, 2020 03:57
-
-
Save vin-e/fd03464fbd6e7a188d3d7d8987b94d26 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains 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
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