Skip to content

Instantly share code, notes, and snippets.

@Almazatun
Last active October 20, 2024 15:53
Show Gist options
  • Save Almazatun/daea630327429b1f3a2c624527ea9e04 to your computer and use it in GitHub Desktop.
Save Almazatun/daea630327429b1f3a2c624527ea9e04 to your computer and use it in GitHub Desktop.
Costume useForm hook
export const useForm = <C, S = { [key: string]: string }>
(
    callback: (C?: any) => void,
    initState: S,
    validator: (validationData: S) => { errors: Array<string>, valid: boolean }
) => {

    const [values, setValues] = useState<S>(initState)

    const [errors, setErrors] = useState<Array<string>>([])
    const [valid, setValid] = useState<boolean>(false)

    const onChange = (event: ChangeEvent<HTMLInputElement>) => {
        event.persist();
        const {name} = event.target
        let value = event.currentTarget.value.trim() !== '' ? event.currentTarget.value : '';
        setValues({
            ...values,
            [name]: value
        })
    }

    const setEmptyValues = () => {
       let emptyData: S = {...initState}
        setValues(emptyData)
    }

    const onSubmit = (event: FormEvent) => {
        event.preventDefault();
        const {errors, valid} = validator(values)
        setErrors(errors)
        setValid(valid)

        setTimeout(() => {
            setErrors([])
        }, 10_000)
    }

    useEffect(() => {
        if (Object.keys(errors).length === 0 && valid) {
            callback()
            setEmptyValues()
        }

    }, [valid])

    return {
        onChange,
        onSubmit,
        values,
        errors
    }
    
    ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment