A hook to help you manage your form state declaratively.
npm install @akshay-nm/use-form-state> A hook to help you manage your form state declaratively.
 
``bash`
npm install --save @akshay-nm/use-form-state
The hook takes an object as configuration. Let's assume config is the configuration object to be passed to the hook.
For each form field, you need:
- value
- onChangeHandler
- showWarning
To generate these, the hook needs:
- name of the field
- default value of the field
- validator
- is the field valid by default
- is this field mandatory (should the field affect the overall form validity or not)
So for each field you have to pass configuration:
`jsx`
{
name: 'nameInCamelCase', // Although I have added a camelize check but still...
default: '', // the default value of field
defaultIsValid: false, // is the field valid by default
mustBeValid: true, // is the field mandatory
validator: (value) => true // the validator
},
You pass the fields as an array named states.
`jsx`
const config = {
states: [
{
name: 'email',
default: '',
defaultIsValid: false,
mustBeValid: true,
validator: () => true
},
{
name: 'password',
default: '',
defaultIsValid: false,
mustBeValid: true,
validator: (val) => val.length > 5
}
],
debug: false // if you want logs
}
`jsx
import React from 'react'
import Login from './Login'
const App = () => {
return
}
export default App
`
`jsx
import React, { useCallback } from 'react'
import useLoginFormState from '@akshay-nm/use-form-state'
const Login = () => {
const {
isValid: formIsValid,
isValidating,
resetForm,
email,
showEmailWarning,
onEmailChange,
password,
showPasswordWarning,
onPasswordChange
} = useFormState({
states: [
{
name: 'email',
default: '',
defaultIsValid: false,
mustBeValid: true,
validator: () => true
},
{
name: 'password',
default: '',
defaultIsValid: false,
mustBeValid: true,
validator: (val) => val.length > 5
}
],
debug: false
})
const login = useCallback(() => {
console.log('Send login request, form is valid: ', formIsValid)
}, [formIsValid])
return (
}
value={email}
onChange={(event) => onEmailChange(event.target.value)}
/>
}
value={password}
onChange={(event) => onPasswordChange(event.target.value)}
type='password'
/>
}
onClick={login}
disabled={isValidating}
>
Login
className={px-2 py-1 border rounded}
onClick={resetForm}
disabled={isValidating}
>
Clear
export default Login
``
MIT © akshay-nm