š Final Form
ā
Zero dependencies
ā
Framework agnostic
ā
Opt-in subscriptions - only update on the state you need!
ā
š„ 3.5k gzipped š„
Installation
npm install --save final-form
or
yarn add final-form
Getting Started
š Final Form works on subscriptions to perform updates based on the
Observer pattern. Both form
and field subscribers must specify exactly which parts of the form state they
want to receive updates about.
import { createForm } from 'final-form'
const form = createForm({
initialValues,
onSubmit,
validate
})
const unsubscribe = form.subscribe(
formState => {
},
{
dirty: true,
valid: true,
values: true
}
})
const unregisterField = form.registerField(
'username',
fieldState => {
const { blur, change, focus, ...rest } = fieldState
},
{
active: true,
dirty: true,
touched: true,
valid: true,
value: true
}
)
form.submit()
Table of Contents
Examples
Demonstrates how š Final Form can be used inside a React component to manage
form state. It also shows just how much
š React Final Form
does for you out of the box.
For more examples using React, see
š React Final Form Examples.
Libraries
A form state management system for React that uses š Final Form under the hood.
A form state management system for Vue that uses š Final Form under the hood.
API
The following can be imported from final-form
.
createForm: (config: Config) => FormApi
Creates a form instance. It takes a Config
and returns a
FormApi
.
fieldSubscriptionItems: string[]
An Ć la carte list of all the possible things you can subscribe to for a
field. Useful for subscribing to everything.
formSubscriptionItems: string[]
An Ć la carte list of all the possible things you can subscribe to for a form.
Useful for subscribing to everything.
FORM_ERROR: Symbol
A special Symbol
key used to return a whole-form error inside error objects
returned from validation or submission.
getIn(state: Object, complexKey: string): any
setIn(state: Object, key: string, value: any): Object
version: string
The current used version of š Final Form.
Types
Config
debug?: DebugFunction
initialValues?: Object
The initial values of your form. These will also be used to compare against the
current values to calculate pristine
and dirty
.
mutators?: { [string]: Mutator }
Optional named mutation functions.
onSubmit: (values: Object, form: FormApi, callback: ?(errors: ?Object) => void) => ?Object | Promise<?Object> | void
Function to call when the form is submitted. There are three possible ways to
write an onSubmit
function:
- Synchronously: returns
undefined
on success, or an Object
of submission
errors on failure - Asynchronously with a callback: returns
undefined
, calls callback()
with
no arguments on success, or with an Object
of submission errors on failure. - Asynchronously with a
Promise
: returns a Promise<?Object>
that resolves
with no value on success or resolves with an Object
of submission errors
on failure. The reason it resolves with errors is to leave rejection for
when there is a server or communications error.
Submission errors must be in the same shape as the values of the form. You may
return a generic error for the whole form (e.g. 'Login Failed'
) using the
special FORM_ERROR
symbol key.
validate?: (values: Object) => Object | Promise<Object>
A whole-record validation function that takes all the values of the form and
returns any validation errors. There are three possible ways to write a
validate
function:
- Synchronously: returns
{}
or undefined
when the values are valid, or an
Object
of validation errors when the values are invalid. - Asynchronously with a
Promise
: returns a Promise<?Object>
that resolves
with no value on success or resolves with an Object
of validation errors
on failure. The reason it resolves with errors is to leave rejection for
when there is a server or communications error.
Validation errors must be in the same shape as the values of the form. You may
return a generic error for the whole form using the special FORM_ERROR
symbol
key.
An optional callback for debugging that returns the form state and the states of
all the fields. It's called on every state change. A typical thing to pass in
might be console.log
.
validateOnBlur?: boolean
If true
, validation will happen on blur. If false
, validation will happen on
change. Defaults to false
.
DebugFunction: (state: FormState, fieldStates: { [string]: FieldState }) => void
Decorator: (form: FormApi) => Unsubscribe
A function that decorates a
form by subscribing to it and making changes as the form state changes, and
returns an Unsubscribe
function to detach itself from
the form. e.g.
š Final Form Calculate.
FieldConfig
isEqual?: (a: any, b: any) => boolean
A function to determine if two values are equal. Defaults to ===
.
validate?: (value: ?any, allValues: Object) => ?any
A field-level validation function to validate a single field value. Returns an
error if the value is not valid, or undefined
if the value is valid.
validateFields?: string[]
An array of field names to validate when this field changes. If undefined
,
every field will be validated when this one changes; if []
, only this
field will have its field-level validation function called when it changes; if
other field names are specified, those fields and this one will be validated
when this field changes.
FieldState
FieldState
is an object containing:
active?: boolean
Whether or not the field currently has focus.
blur: () => void
A function to blur the field (mark it as inactive).
change: (value: any) => void
A function to change the value of the field.
data?: Object
A place for arbitrary values to be placed by mutators.
dirty?: boolean
true
when the value of the field is !==
the initial value, false
if the
values are ===
.
error?: any
The current validation error for this field.
focus: () => void
A function to focus the field (mark it as active).
initial?: any
The initial value of the field. undefined
if it was never initialized.
invalid?: boolean
true
if the field has a validation error or a submission error. false
otherwise.
length?: number
The length of the array if the value is an array. undefined
otherwise.
name: string
The name of the field.
pristine?: boolean
true
if the current value is ===
to the initial value, false
if the values
are !===
.
submitError?: any
The submission error for this field.
submitFailed?: boolean
true
if a form submission has been tried and failed. false
otherwise.
submitSucceeded?: boolean
true
if the form has been successfully submitted. false
otherwise.
touched?: boolean
true
if this field has ever gained and lost focus. false
otherwise. Useful
for knowing when to display error messages.
valid?: boolean
true
if this field has no validation or submission errors. false
otherwise.
value?: any
The value of the field.
visited?: boolean
true
if this field has ever gained focus.
FieldSubscriber: (state: FieldState) => void
FieldSubscription: { [string]: boolean }
FieldSubscription
is an object containing the following:
active?: boolean
When true
the FieldSubscriber
will be notified of changes to the active
value in FieldState
.
data?: boolean
When true
the FieldSubscriber
will be notified of changes to the data
value in FieldState
.
dirty?: boolean
When true
the FieldSubscriber
will be notified of changes to the dirty
value in FieldState
.
error?: boolean
When true
the FieldSubscriber
will be notified of changes to the error
value in FieldState
.
initial?: boolean
When true
the FieldSubscriber
will be notified of changes to the initial
value in FieldState
.
invalid?: boolean
When true
the FieldSubscriber
will be notified of changes to the invalid
value in FieldState
.
length?: boolean
When true
the FieldSubscriber
will be notified of changes to the length
value in FieldState
.
pristine?: boolean
When true
the FieldSubscriber
will be notified of changes to the pristine
value in FieldState
.
submitError?: boolean
When true
the FieldSubscriber
will be notified of changes to the
submitError
value in FieldState
.
submitFailed?: boolean
When true
the FieldSubscriber
will be notified of changes to the
submitFailed
value in FieldState
.
submitSucceeded?: boolean
When true
the FieldSubscriber
will be notified of changes to the
submitSucceeded
value in FieldState
.
touched?: boolean
When true
the FieldSubscriber
will be notified of changes to the touched
value in FieldState
.
valid?: boolean
When true
the FieldSubscriber
will be notified of changes to the valid
value in FieldState
.
value?: boolean
When true
the FieldSubscriber
will be notified of changes to the value
value in FieldState
.
visited?: boolean
When true
the FieldSubscriber
will be notified of changes to the visited
value in FieldState
.
FormApi
batch: (fn: () => void) => void)
Allows batch updates by silencing notifications while the fn
is running.
Example:
form.batch(() => {
form.change('firstName', 'Erik')
form.change('lastName', 'Rasmussen')
})
blur: (name: string) => void
Blurs (marks inactive) the given field.
change: (name: string, value: ?any) => void
Changes the value of the given field.
focus: (name: string) => void
Focuses (marks active) the given field.
getRegisteredFields: () => string[]
Returns a list of all the currently registered fields.
getState: () => FormState
A way to request the current state of the form without subscribing.
initialize: (values: Object) => void
Initializes the form to the values provided. All the values will be set to these
values, and dirty
and pristine
will be calculated by performing a
shallow-equals between the current values and the values last initialized with.
The form will be pristine
after this call.
mutators: ?{ [string]: Function }
The state-bound versions of the mutators provided to Config
.
submit: () => ?Promise<?Object>
Submits the form if there are currently no validation errors. It may return
undefined
or a Promise
depending on the nature of the onSubmit
configuration value given to the form when it was created.
subscribe: (subscriber: FormSubscriber, subscription: FormSubscription) => Unsubscribe
Subscribes to changes to the form. The subscriber
will only be called when
values specified in subscription
change. A form can have many subscribers.
registerField: RegisterField
Registers a new field and subscribes to changes to it. The subscriber
will
only be called when the values specified in subscription
change. More than
one subscriber can subscribe to the same field.
This is also where you may provide an optional field-level validation function
that should return undefined
if the value is valid, or an error. It can
optionally return a Promise
that resolves (not rejects) to undefined
or an
error.
reset: () => void
Resets the values back to the initial values the form was initialized with. Or
empties all the values if the form was not initialized.
FormState
active?: string
The name of the currently active field. undefined
if none are active.
dirty?: boolean
true
if the form values are different from the values it was initialized with.
false
otherwise. Comparison is done with shallow-equals.
error?: any
The whole-form error returned by a validation function under the FORM_ERROR
key.
errors?: Object
An object containing all the current validation errors. The shape will match the
shape of the form's values.
initialValues?: Object
The values the form was initialized with. undefined
if the form was never
initialized.
invalid?: boolean
true
if any of the fields or the form has a validation or submission error.
false
otherwise. Note that a form can be invalid even if the errors do not
belong to any currently registered fields.
pristine?: boolean
true
if the form values are the same as the initial values. false
otherwise.
Comparison is done with shallow-equals.
submitError?: any
The whole-form submission error returned by onSubmit
under the FORM_ERROR
key.
submitErrors?: Object
An object containing all the current submission errors. The shape will match the
shape of the form's values.
submitFailed?: boolean
true
if the form was submitted, but the submission failed with submission
errors. false
otherwise.
submitSucceeded?: boolean
true
if the form was successfully submitted. false
otherwise.
submitting?: boolean
true
if the form is currently being submitted asynchronously. false
otherwise.
valid?: boolean
true
if neither the form nor any of its fields has a validation or submission
error. false
otherwise. Note that a form can be invalid even if the errors do
not belong to any currently registered fields.
validating?: boolean
true
if the form is currently being validated asynchronously. false
otherwise.
values?: Object
The current values of the form.
FormSubscriber: (state: FormState) => void
FormSubscription: { [string]: boolean }
FormSubscription
is an object containing the following:
active?: boolean
When true
the FormSubscriber
will be notified of changes to the active
value in FormState
.
dirty?: boolean
When true
the FormSubscriber
will be notified of changes to the dirty
value in FormState
.
error?: boolean
When true
the FormSubscriber
will be notified of changes to the error
value in FormState
.
errors?: boolean
When true
the FormSubscriber
will be notified of changes to the errors
value in FormState
.
initialValues?: boolean
When true
the FormSubscriber
will be notified of changes to the
initialValues
value in FormState
.
invalid?: boolean
When true
the FormSubscriber
will be notified of changes to the invalid
value in FormState
.
pristine?: boolean
When true
the FormSubscriber
will be notified of changes to the pristine
value in FormState
.
submitError?: boolean
When true
the FormSubscriber
will be notified of changes to the
submitError
value in FormState
.
submitErrors?: boolean
When true
the FormSubscriber
will be notified of changes to the
submitErrors
value in FormState
.
submitFailed?: boolean
When true
the FormSubscriber
will be notified of changes to the
submitFailed
value in FormState
.
submitSucceeded?: boolean
When true
the FormSubscriber
will be notified of changes to the
submitSucceeded
value in FormState
.
submitting?: boolean
When true
the FormSubscriber
will be notified of changes to the submitting
value in FormState
.
valid?: boolean
When true
the FormSubscriber
will be notified of changes to the valid
value in FormState
.
validating?: boolean
When true
the FormSubscriber
will be notified of changes to the validating
value in FormState
.
values?: boolean
When true
the FormSubscriber
will be notified of changes to the values
value in FormState
.
InternalFieldState
Very similar to the published FieldState
.
active: boolean
Whether or not the field currently has focus.
blur: () => void
A function to blur the field (mark it as inactive).
change: (value: any) => void
A function to change the value of the field.
data: Object
A place for arbitrary values to be placed by mutators.
focus: () => void
A function to focus the field (mark it as active).
isEqual: (a: any, b: any) => boolean
A function to determine if two values are equal. Used to calculate
pristine
/dirty
.
name: string
The name of the field.
pristine: boolean
true
if the current value is ===
to the initial value, false
if the values
are !===
.
touched: boolean
true
if this field has ever gained and lost focus. false
otherwise. Useful
for knowing when to display error messages.
validateFields: ?(string[])
Fields to validate when this field value changes.
validators: { [number]: (value: ?any, allValues: Object) => ?any | Promise<?any> } }
Field-level validators for each field that is registered.
valid: boolean
true
if this field has no validation or submission errors. false
otherwise.
visited: boolean
true
if this field has ever gained focus.
InternalFormState
Very similar to the published FormState
, with a few minor
differences.
active?: string
The name of the currently active field. undefined
if none are active.
error?: any
The whole-form error returned by a validation function under the FORM_ERROR
key.
errors: Object
An object containing all the current validation errors. The shape will match the
shape of the form's values.
initialValues?: Object
The values the form was initialized with. undefined
if the form was never
initialized.
pristine: boolean
true
if the form values are the same as the initial values. false
otherwise.
Comparison is done with shallow-equals.
submitError: any
The whole-form submission error returned by onSubmit
under the FORM_ERROR
key.
submitErrors?: Object
An object containing all the current submission errors. The shape will match the
shape of the form's values.
submitFailed: boolean
true
if the form was submitted, but the submission failed with submission
errors. false
otherwise.
submitSucceeded: boolean
true
if the form was successfully submitted. false
otherwise.
submitting: boolean
true
if the form is currently being submitted asynchronously. false
otherwise.
valid: boolean
true
if neither the form nor any of its fields has a validation or submission
error. false
otherwise. Note that a form can be invalid even if the errors do
not belong to any currently registered fields.
validating: number
The number of asynchronous validators currently running.
values: Object
The current values of the form.
MutableState
MutableState
is an object containing the following:
formState: InternalFormState
The InternalFormState
.
fields: { [string]: InternalFieldState }
An object of InternalFieldState
s.
Mutator: (args: any[], state: MutableState, tools: Tools) => any
A mutator function that takes some arguments, the internal form
MutableState
, and some Tools
and optionally
modifies the form state.
RegisterField: (name: string, subscriber: FieldSubscriber, subscription: FieldSubscription, config?: FieldConfig) => Unsubscribe
Takes a name, and a
FieldSubscriber
,
FieldSubscriber
, and a
FieldConfig
and registers a field subscription.
Tools
An object containing:
Tools.changeValue: (state: MutableState, name: string, mutate: (value: any) => any) => void
A utility function to modify a single field value in form state. mutate()
takes the old value and returns the new value.
Tools.getIn: (state: Object, complexKey: string) => any
A utility function to get any arbitrarily deep value from an object using
dot-and-bracket syntax (e.g. some.deep.values[3].whatever
).
Tools.setIn: (state: Object, key: string, value: any) => Object
A utility function to set any arbitrarily deep value inside an object using
dot-and-bracket syntax (e.g. some.deep.values[3].whatever
). Note: it does
not mutate the object, but returns a new object.
Tools.shallowEqual: (a: any, b: any) => boolean
A utility function to compare the keys of two objects. Returns true
if the
objects have the same keys and the values are ===
, false
otherwise.
Unsubscribe : () => void
Unsubscribes a listener.