0

I found this custom hook to validate input values on github

https://github.com/WebDevSimplified/useful-custom-react-hooks/blob/main/src/18-useStateWithValidation/StateWithValidationComponent.js

import { useState, useCallback } from "react"

export default function useStateWithValidation(validationFunc, initialValue) {
  const [state, setState] = useState(initialValue)
  const [isValid, setIsValid] = useState(() => validationFunc(state))

  const onChange = useCallback(
    nextState => {
      const value =
        typeof nextState === "function" ? nextState(state) : nextState
      setState(value)
      setIsValid(validationFunc(value))
    },
    [validationFunc]
  )

  return [state, onChange, isValid]
} 

but i wanted to use it with typescript, but can't get it right Here is what i tried:

import { useState, useCallback } from 'react'

export default function useStateWithValidation(
  validationFunc: (value: string) => boolean,
  initialValue: string
) {
  const [state, setState] = useState<string>(initialValue)
  const [isValid, setIsValid] = useState(() => validationFunc(state))

  const onChange = useCallback(
    (nextState: string | ((state: string) => string)) => {
      const value =
        typeof nextState === 'function' ? nextState(state) : nextState
      setState(value)
      setIsValid(validationFunc(value))
    },
    [validationFunc]
  )

  return [state, onChange, isValid]
} 

and the error i get when trying to use it

Error: (property) React.InputHTMLAttributes.value?: string | number | readonly string[] | undefined Type 'string | boolean | ((nextState: string | ((state: string) => string)) => void)' is not assignable to type 'string | number | readonly string[] | undefined'. Type 'false' is not assignable to type 'string | number | readonly string[] | undefined'.ts(2322) index.d.ts(2251, 9): The expected type comes from property 'value' which is declared here on type 'DetailedHTMLProps<InputHTMLAttributes, HTMLInputElement>'

0 Answers0