I am fooling around with hooks in React and I'm stumbling against decisions that I need to make regarding implementation. Below is the code for the custom useForm hook which can be used to hook up forms to validation using Yub schema's.
Currently you can pass a callback function to the useForm that gets called when all the values are valid but this is where I'm not 100% sure what the best approach would be. Callback pattern or a promise or something I have not thought of?
I use flow for type annotations and I would love you guys to give me some feedback. Please do bash it!
import { useState } from 'react'
import { mapYubValidationSchemaErrors } from '@domain/helpers'
type YubValidationSchema = any
function useForm(validationSchema: YubValidationSchema, callback: () => void) {
const [values, setValues] = useState({})
const [errors, setErrors] = useState({})
async function handleSubmit(event: SyntheticEvent<HTMLFormElement>) {
event.preventDefault()
try {
await validationSchema.validate(values, { abortEarly: false })
callback()
} catch (errorResult) {
setErrors(
mapYubValidationSchemaErrors(errorResult.inner),
)
}
}
function handleChange(event: SyntheticInputEvent<HTMLInputElement>) {
event.persist()
const newValues = {
...values,
[event.target.name]: event.target.value,
}
setValues(newValues)
}
return {
values,
errors,
handleSubmit,
handleChange,
}
}
export default useForm
The code to use it can be as follows
function onValidated() {
// Do something
}
const {
errors,
handleChange,
handleSubmit,
} = useForm(validationSchema, onValidated)