Created
April 21, 2023 08:08
-
-
Save chihabhajji/0e7b391cd3093d64e4cefc2eee204e1a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useForm, SubmitHandler, SubmitErrorHandler, ValidationMode } from 'react-hook-form'; | |
import { z } from 'zod'; | |
import { zodResolver } from "@hookform/resolvers/zod"; | |
import { BaseSyntheticEvent, useState } from "react"; | |
interface UseValidationProps<T extends z.ZodType<any, any>> { | |
schema: T; | |
onSubmit: SubmitHandler<z.infer<T>>; | |
} | |
export const useZodForm = <T extends z.ZodObject<any, any>>({ schema, onSubmit }: UseValidationProps<T>, mode?: keyof ValidationMode) => { | |
const [submitError, setSubmitError] = useState<Error | null>(null); | |
const { register, handleSubmit, formState: { errors, isSubmitting, isLoading }, ...rest } = useForm<z.infer<T>>({ | |
mode: mode ?? 'onBlur', | |
resolver: zodResolver(schema), | |
}); | |
const onSubmitHandler = async (data: z.infer<T>) => { | |
setSubmitError(null) | |
try { | |
const validatedData = await schema.safeParseAsync(data); | |
if (validatedData.success) await onSubmit(validatedData.data); | |
else if (process.env.NODE_ENV === 'development') console.log(validatedData.error); | |
} catch (e) { | |
if (e instanceof Error) setSubmitError(e); | |
} | |
}; | |
return { | |
register, | |
handleSubmit: handleSubmit(onSubmitHandler), | |
errors, | |
isSubmitting, | |
submitError, | |
isLoading, | |
rest | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment