Initial values
In most cases you should set initialValues
:
setValues handler
With form.setValues
you can set all form values, for example you can set values after you have received a response from the backend API:
setValues partial
form.setValues
can also be used to set multiple values at once, payload will be shallow merged with current values state:
Initialize form
When called form.initialize
handler sets initialValues
and values
to the same value
and marks form as initialized. It can be used only once, next form.initialize
calls
are ignored.
form.initialize
is useful when you want to sync form values with backend API response:
Example with TanStack Query (react-query):
Note that form.initialize
will erase all values that were set before it was called.
It is usually a good idea to set readOnly
or disabled
on all form fields before
form.initialize
is called to prevent data loss. You can implement this with
enhanceGetInputProps:
setFieldValue handler
form.setFieldValue
handler allows to set value of the field at given path:
reset handler
form.reset
handler sets values to initialValues
and clear all errors:
setInitialValues handler
form.setInitialValues
handler allows to update initialValues
after form was initialized:
transformValues
Use transformValues
to transform values before they get submitted in onSubmit
handler.
For example, it can be used to merge several fields into one or to convert types:
Get transformed values
You can get transformed values outside of form.onSubmit
method by calling form.getTransformedValues
.
It accepts values
that need to be transformed as optional argument, if it is not provided, then
the result of form.getValues()
transformation will be returned instead:
onValuesChange
onValuesChange
function is called every time form values change, use it
instead of useEffect
to subscribe to form values changes:
form.watch
form.watch
is an effect function that allows subscribing to changes of a
specific form field. It accepts field path and a callback function that is
called with new value, previous value, touched and dirty field states:
Note that form.watch
uses useEffect
under the hood – all hooks rules apply.
For example, you cannot use form.watch
conditionally or inside loops.
Get values type
Get transformed values type
To get transformed values (output of transformValues) use TransformedValues
type.
It is useful when you want to create a custom submit function:
Set values type
By default, form values types will be inferred from initialValues
.
To avoid that, you can pass type to useForm
hook, this approach is useful when
types cannot be correctly inferred or when you want to provide more specific types: