hooks.ts 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. import { useState } from 'react'
  2. import { useDebounceFn } from 'ahooks'
  3. import type { DebouncedFunc } from 'lodash-es'
  4. import { ValidatedStatus } from './declarations'
  5. import type { ValidateCallback, ValidateValue, ValidatedStatusState } from './declarations'
  6. export const useValidate: (value: ValidateValue) => [DebouncedFunc<(validateCallback: ValidateCallback) => Promise<void>>, boolean, ValidatedStatusState] = (value) => {
  7. const [validating, setValidating] = useState(false)
  8. const [validatedStatus, setValidatedStatus] = useState<ValidatedStatusState>({})
  9. const { run } = useDebounceFn(async (validateCallback: ValidateCallback) => {
  10. if (!validateCallback.before(value)) {
  11. setValidating(false)
  12. setValidatedStatus({})
  13. return
  14. }
  15. setValidating(true)
  16. if (validateCallback.run) {
  17. const res = await validateCallback?.run(value)
  18. setValidatedStatus(
  19. res.status === 'success'
  20. ? { status: ValidatedStatus.Success }
  21. : { status: ValidatedStatus.Error, message: res.message })
  22. setValidating(false)
  23. }
  24. }, { wait: 1000 })
  25. return [run, validating, validatedStatus]
  26. }