diff --git a/README.md b/README.md index 808939d..6ef0082 100644 --- a/README.md +++ b/README.md @@ -7,20 +7,73 @@ ## Install ```bash -npm install --save @colorfy-software/use-form +yarn add @colorfy-software/use-form ``` ## Usage ```tsx -import * as React from "react"; +import * as React from 'react' +import useForm, { hasLengthyError, hasEmailError, FormValidatorType } from '@colorfy-software/use-form' -import { useMyHook } from "@colorfy-software/use-form"; +// Define the form fields +const FORM_SCHEMA = { + email: '', + password: '', +} + +// Define the form validators +// Validators should return either false or the error +// this allows for error chaining +const FORM_VALIDATION: FormValidatorType = { + email: { + validatorFn: (value) => hasLengthyError(value) || hasEmailError(value), + }, + password: { + validatorFn: (value) => hasLengthyError(value), + }, +} const Example = () => { - const example = useMyHook(); - return
{example}
; -}; + // Submit function that will be called when the form is submitted + const onSubmitForm = async (form: typeof FORM_SCHEMA) => { + console.log('onSubmitForm', { + email: form.email, + password: form.password, + }) + } + + const { state, onHandleChange, onHandleSubmit, errors } = useForm(FORM_SCHEMA, FORM_VALIDATION, onSubmitForm) + + return ( +
+

useForm

+ {/* Show errors if error exists */} + {errors.email &&

{errors.email}

} + onHandleChange('email', e.target.value)} + /> + + {errors.password &&

{errors.password}

} + onHandleChange('password', e.target.value)} + /> + + {/* Call the submit function when the form is submitted. This handles validation and error chaining */} + +
+ ) +} ``` ## License