forms.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { useEffect, useState, FormEvent, ChangeEvent, SyntheticEvent } from 'react'
  2. import TextInput from './TextInput'
  3. export interface InputProps {
  4. id: string,
  5. name: string,
  6. value: any,
  7. onChange: (event: SyntheticEvent) => void,
  8. onBlur: (event: SyntheticEvent) => void,
  9. placeholder: string,
  10. label: string
  11. }
  12. interface FormHandler {
  13. inputProps: (name: string) => InputProps,
  14. handleChange: (event: SyntheticEvent) => void,
  15. handleBlur: (event: SyntheticEvent) => void,
  16. values: Dict,
  17. errors: Dict,
  18. isSubmitting: boolean
  19. }
  20. /**
  21. * Provides hooks for forms.
  22. *
  23. * @remarks
  24. * You can use it like this
  25. * ```ts
  26. * const {inputParams, formParams} = useFormHandler()
  27. * ```
  28. *
  29. * @param initialValues - Initial values of inputs
  30. * @param validate - validation function for the form
  31. * @returns hooks to handle the form
  32. */
  33. function useFormHandler(
  34. initialValues: Dict,
  35. validate?: (values: Dict) => {}
  36. ): FormHandler {
  37. console.log('useFormHandler called.', initialValues)
  38. const [values, setValues] = useState(initialValues)
  39. const [errors, setErrors] = useState({})
  40. const [isSubmitting, setIsSubmitting] = useState(false)
  41. useEffect(() => {
  42. if (isSubmitting) {
  43. const noErrors = Object.keys(errors).length === 0
  44. if (noErrors) {
  45. console.log('no errors while submitting.')
  46. } else {
  47. console.log('errors while submitting,')
  48. }
  49. setIsSubmitting(false)
  50. }
  51. }, [errors])
  52. function handleChange(event: SyntheticEvent): void {
  53. setValues({
  54. ...values,
  55. [(event.target as HTMLInputElement).name]:
  56. (event.target as HTMLInputElement).value
  57. })
  58. }
  59. function handleBlur(event: SyntheticEvent): void {
  60. if (validate) {
  61. const validationErrors = validate(values)
  62. setErrors(validationErrors)
  63. }
  64. }
  65. function inputProps(name: string, label?: string): InputProps {
  66. if (!values.hasOwnProperty(name)) {
  67. throw Error(`${name} is not an existing field.`)
  68. }
  69. return {
  70. id: name,
  71. name,
  72. value: values[name],
  73. onChange: handleChange,
  74. onBlur: handleBlur,
  75. placeholder: label || name,
  76. label: label || name
  77. }
  78. }
  79. return {
  80. inputProps,
  81. handleChange,
  82. handleBlur,
  83. values,
  84. errors,
  85. isSubmitting
  86. }
  87. }
  88. export { useFormHandler, TextInput }