forms.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { useEffect, useState } from 'react'
  2. type FormHandler = {
  3. inputProps: (name: string) => {},
  4. submitProps: () => {},
  5. handleSubmit: (event: Event) => void,
  6. handleChange: (event: Event) => void,
  7. handleBlur: (event: Event) => void,
  8. values: {},
  9. errors: {},
  10. isSubmitting: boolean
  11. }
  12. function useFormHandler(
  13. initialState: {},
  14. validate: (values: {}) => {}
  15. ): FormHandler {
  16. const [values, setValues] = useState(initialState)
  17. const [errors, setErrors] = useState({})
  18. const [isSubmitting, setIsSubmitting] = useState(false)
  19. useEffect(() => {
  20. if (isSubmitting) {
  21. const noErrors = Object.keys(errors).length === 0
  22. if (noErrors) {
  23. console.log('no errors while submitting.')
  24. } else {
  25. console.log('errors while submitting,')
  26. }
  27. setIsSubmitting(false)
  28. }
  29. }, [errors])
  30. function handleSubmit(
  31. event: Event,
  32. callback?: (event: Event, data?: {}) => void, data?: {}
  33. ): void {
  34. event.preventDefault()
  35. const validationErrors = validate(values)
  36. setErrors(validationErrors)
  37. setIsSubmitting(true)
  38. if (callback === null) {
  39. callback(event, data)
  40. }
  41. }
  42. function handleChange(event: Event): void {
  43. setValues({
  44. ...values,
  45. [(event.target as HTMLInputElement).name]:
  46. (event.target as HTMLInputElement).value
  47. })
  48. }
  49. function handleBlur(event: Event): void {
  50. const validationErrors = validate(values)
  51. setErrors(validationErrors)
  52. }
  53. function inputProps(name: string): {} {
  54. if (!initialState.hasOwnProperty(name)) {
  55. throw Error(`${name} is not an existing field.`)
  56. }
  57. return {
  58. name,
  59. id: name,
  60. onChange: handleChange,
  61. onBlur: handleBlur,
  62. value: values[name]
  63. }
  64. }
  65. function submitProps(): {} {
  66. return {
  67. onSubmit: handleSubmit
  68. }
  69. }
  70. return {
  71. inputProps,
  72. submitProps,
  73. handleSubmit,
  74. handleChange,
  75. handleBlur,
  76. values,
  77. errors,
  78. isSubmitting
  79. }
  80. }
  81. export default useFormHandler