123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- import { useEffect, useState } from 'react'
- type FormHandler = {
- inputProps: (name: string) => {},
- submitProps: () => {},
- handleSubmit: (event: Event) => void,
- handleChange: (event: Event) => void,
- handleBlur: (event: Event) => void,
- values: {},
- errors: {},
- isSubmitting: boolean
- }
- function useFormHandler(
- initialState: {},
- validate: (values: {}) => {}
- ): FormHandler {
- const [values, setValues] = useState(initialState)
- const [errors, setErrors] = useState({})
- const [isSubmitting, setIsSubmitting] = useState(false)
- useEffect(() => {
- if (isSubmitting) {
- const noErrors = Object.keys(errors).length === 0
- if (noErrors) {
- console.log('no errors while submitting.')
- } else {
- console.log('errors while submitting,')
- }
- setIsSubmitting(false)
- }
- }, [errors])
- function handleSubmit(
- event: Event,
- callback?: (event: Event, data?: {}) => void, data?: {}
- ): void {
- event.preventDefault()
- const validationErrors = validate(values)
- setErrors(validationErrors)
- setIsSubmitting(true)
- if (callback === null) {
- callback(event, data)
- }
- }
- function handleChange(event: Event): void {
- setValues({
- ...values,
- [(event.target as HTMLInputElement).name]:
- (event.target as HTMLInputElement).value
- })
- }
- function handleBlur(event: Event): void {
- const validationErrors = validate(values)
- setErrors(validationErrors)
- }
- function inputProps(name: string): {} {
- if (!initialState.hasOwnProperty(name)) {
- throw Error(`${name} is not an existing field.`)
- }
- return {
- name,
- id: name,
- onChange: handleChange,
- onBlur: handleBlur,
- value: values[name]
- }
- }
- function submitProps(): {} {
- return {
- onSubmit: handleSubmit
- }
- }
- return {
- inputProps,
- submitProps,
- handleSubmit,
- handleChange,
- handleBlur,
- values,
- errors,
- isSubmitting
- }
- }
- export default useFormHandler
|