From 32363d7689dfd37873a0cef8ac8c5f1004558545 Mon Sep 17 00:00:00 2001 From: Manjush Shetty Date: Thu, 23 Jan 2025 10:11:04 +0530 Subject: [PATCH] (snippet): Added useForm hook --- snippets/react/hook/use-form.mdx | 96 ++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 snippets/react/hook/use-form.mdx diff --git a/snippets/react/hook/use-form.mdx b/snippets/react/hook/use-form.mdx new file mode 100644 index 0000000..ca7a8b3 --- /dev/null +++ b/snippets/react/hook/use-form.mdx @@ -0,0 +1,96 @@ +export const metadata = { + name: "useForm", + description: "useForm hook simplifies handling forms in React.", + keywords: ["form"], + contributors: ["manjushsh"], +}; + +```tsx +import { useState, ChangeEvent, FormEvent } from 'react'; + +type ValidationFunction = (values: T) => Promise; + +export function useForm>( + initialValues: T, + onSubmit: (values: T) => void, + validate: ValidationFunction +) { + const [values, setValues] = useState(initialValues); + const [errors, setErrors] = useState>>({}); + const [isSubmitting, setIsSubmitting] = useState(false); + + const handleChange = (e: ChangeEvent) => { + const { name, value } = e.target; + setValues(prev => ({ ...prev, [name]: value })); + setErrors(prev => ({ ...prev, [name]: '' })); + }; + + const handleSubmit = async (e: FormEvent) => { + e.preventDefault(); + setIsSubmitting(true); + setErrors({}); + + try { + const isValid = await validate(values); + if (isValid) { + onSubmit(values); + } else { + setErrors(prev => ({ ...prev, form: 'Validation failed. Please check your inputs.' })); + } + } catch (error) { + setErrors(prev => ({ ...prev, form: `An error occurred. Please try again. ${JSON.stringify(error)}` })); + } finally { + setIsSubmitting(false); + } + }; + + return { values, errors, isSubmitting, handleChange, handleSubmit }; +} +``` + +```tsx +import React from 'react'; +import { useForm } from './hooks/useForm'; + +const validate = async (values) => { + const errors = {}; + if (!values.username) { + errors.username = 'Username is required'; + } + if (!values.email) { + errors.email = 'Email is required'; + } + return Object.keys(errors).length === 0; +}; + +const MyForm = () => { + const initialValues = { username: '', email: '' }; + + const onSubmit = (values) => { + console.log('Form submitted successfully with values:', values); + }; + + const { values, errors, isSubmitting, handleChange, handleSubmit } = useForm(initialValues, onSubmit, validate); + + return ( +
+
+ + {errors.username && {errors.username}} +
+
+ + {errors.email && {errors.email}} +
+ {errors.form &&
{errors.form}
} + +
+ ); +}; +```