Skip to content

Instantly share code, notes, and snippets.

@ScreamZ
Created September 15, 2021 10:56
Show Gist options
  • Save ScreamZ/36af8ccc4db8675b8f8ff64eb4e00ca1 to your computer and use it in GitHub Desktop.
Save ScreamZ/36af8ccc4db8675b8f8ff64eb4e00ca1 to your computer and use it in GitHub Desktop.
Use form hooks Typesript
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm, UseFormProps, UseFormReturn } from 'react-hook-form';
import * as Yup from 'yup';
/**
* This function is type inference ready and will auto-validate the useForm with the proper values.
*
* If you don't already have the schema or use a dynamic schema, consider useFormWithSchemaBuilder()
*
* @param schema - A valid you schema
* @param useFormProps
* @returns
*/
export function useFormWithSchema<T extends Yup.AnyObjectSchema>(
schema: T,
useFormProps?: UseFormProps<Yup.Asserts<T>>,
): UseFormReturn<Yup.Asserts<T>> {
return useForm({ ...useFormProps, resolver: yupResolver(schema) });
}
/**
* Use this to prevent importing yup library in your components, if you don't already have the schema, and if you want to have a dynamic schema values.
* This is rebuild on each render.
* This function is type inference ready and will auto-validate the useForm with the proper values.
*
* If you have already the schema or use a static schema, consider useFormWithSchema()
*
* @param schemaBuilder - Should return a validation schema
* @param useFormProps Do not provide "resolver" value as it will be ignored.
* @returns
*/
export function useFormWithSchemaBuilder<T extends Yup.AnyObjectSchema>(
schemaBuilder: (yup: typeof Yup) => T,
useFormProps?: UseFormProps<Yup.Asserts<T>>,
): UseFormReturn<Yup.Asserts<T>> {
return useForm({ ...useFormProps, resolver: yupResolver(schemaBuilder(Yup)) });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment