useForm
A hook to manage state of a form. This is an opinionated hook that will manage all internal state of a form and add isValid
and errorMessages
properties to each field for validation purpose, these properties are derived from the validator function provided to hook and can used to render error messages and to check if the form field is valid.
import { useForm } from 'react-use-custom-hooks';
Usage example
const [formData, setFormData] = useForm(initialState);
- The initial state passed to this hook should be an object with key is the field name and value is an object with
value
andvalidator
properties. The validator function should returnisValid
anderrorMessages
for the particular field upon invoking. For example,
useForm({
name: {
value: '',
validator: value => {
return value.length > 0
? {
isValid: true,
errorMessages: [],
}
: {
isValid: false,
errorMessages: ['Name is required'],
};
},
},
});
- This hook returns two values: form state and form change handler.
- The form state is an object will have the same structure as initialState with
isValid
anderrorMessages
properties added to every field. - The form change handler is a function that takes a field name and a new value and updates the form state.
- For every call to change handler the validation function will be invoked with new value and form state will be updated accordingly.
Playground
Live Editor
Result
Loading...
API
function useAsync(fn: () => any, options?: Options, deps = []);
Options
Property | Description | Type | Default |
---|---|---|---|
successCallback | Callback function on success | Function | - |
errorCallback | Callback function on failure | Function | - |