erikras / final-form
- среда, 29 ноября 2017 г. в 03:15:42
🏁 Framework agnostic, high performance, subscription-based form state management
npm install --save final-formor
yarn add final-formimport { createForm } from 'final-form'
// Create Form
const form = createForm({
initialValues,
onSubmit, // required
validate
})
// Subscribe to form state updates
const unsubscribe = form.subscribe(
formState => {
// Update UI
},
{ // FormSubscription: the list of values you want to be updated about
dirty: true,
valid: true,
values: true
}
})
// Subscribe to field state updates
const unregisterField = form.registerField(
'username',
fieldState => {
// Update field UI
const { blur, change, focus, ...rest } = fieldState
// In addition to the values you subscribe to, field state also
// includes functions that your inputs need to update their state.
},
{ // FieldSubscription: the list of values you want to be updated about
active: true,
dirty: true,
touched: true,
valid: true,
value: true
}
)
// Submit
form.submit() // only submits if all validation passesConfig
FieldState
FieldSubscriber: (state: FieldState) => voidFieldSubscription: { [string]: boolean }
FormApi
batch: (fn: () => void) => void)blur: (name: string) => voidchange: (name: string, value: ?any) => voidfocus: (name: string) => voidinitialize: (values: Object) => voidgetState: () => FormStatesubmit: () => ?Promise<?Object>subscribe: (subscriber: FormSubscriber, subscription: FormSubscription) => UnsubscriberegisterField: (name: string, subscriber: FieldSubscriber, subscription: FieldSubscription, validate?: (value: ?any, allValues: Object) => any | Promise<any>) => Unsubscribereset: () => voidFormState
FormSubscriber: (state: FormState) => voidFormSubscription: { [string]: boolean }
Unsubscribe : () => voidThe following can be imported from final-form.
createForm: (config: Config) => FormApiCreates 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: SymbolA special Symbol key used to return a whole-form error inside error objects
returned from validation or submission.
ConfiginitialValues?: ObjectThe initial values of your form. These will also be used to compare against
the current values to calculate pristine and dirty.
onSubmit: (values: Object, callback: ?(errors: ?Object) => void) => ?Object | Promise<?Object>Function to call when the form is submitted. There are three possible ways to
write an onSubmit function:
undefined on success, or an Object of submission
errors on failureundefined, calls callback() with
no arguments on success, or with an Object of submission errors on failure.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) => void) => 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:
{} or undefined when the values are valid, or an
Object of validation errors when the values are invalid.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.
debug?: (state: FormState, fieldStates: { [string]: FieldState }) => voidAn 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?: booleanIf true, validation will happen on blur. If false, validation will happen on
change. Defaults to false.
FieldStateFieldState is an object containing:
active?: booleanWhether or not the field currently has focus.
blur: () => voidA function to blur the field (mark it as inactive).
change: (value: any) => voidA function to change the value of the field.
dirty?: booleantrue when the value of the field is !== the initial value, false if the
values are ===.
error?: anyThe current validation error for this field.
focus: () => voidA function to focus the field (mark it as active).
initial?: anyThe initial value of the field. undefined if it was never initialized.
invalid?: booleantrue if the field has a validation error or a submission error. false
otherwise.
name: stringThe name of the field.
pristine?: booleantrue if the current value is === to the initial value, false if the values
are !===.
submitError?: anyThe submission error for this field.
submitFailed?: booleantrue if a form submission has been tried and failed. false otherwise.
submitSucceeded?: booleantrue if the form has been successfully submitted. false otherwise.
touched?: booleantrue if this field has ever gained and lost focus. false otherwise. Useful
for knowing when to display error messages.
valid?: booleantrue if this field has no validation or submission errors. false otherwise.
visited?: booleantrue if this field has ever gained focus.
FieldSubscriber: (state: FieldState) => voidFieldSubscription: { [string]: boolean }FieldSubscription is an object containing the following:
active?: booleanWhen true the FieldSubscriber will be notified of changes to the active
value in FieldState.
dirty?: booleanWhen true the FieldSubscriber will be notified of changes to the dirty
value in FieldState.
error?: booleanWhen true the FieldSubscriber will be notified of changes to the error
value in FieldState.
initialValues?: booleanWhen true the FieldSubscriber will be notified of changes to the
initialValues value in FieldState.
invalid?: booleanWhen true the FieldSubscriber will be notified of changes to the invalid
value in FieldState.
pristine?: booleanWhen true the FieldSubscriber will be notified of changes to the pristine
value in FieldState.
submitting?: booleanWhen true the FieldSubscriber will be notified of changes to the
submitting value in FieldState.
submitFailed?: booleanWhen true the FieldSubscriber will be notified of changes to the
submitFailing value in FieldState.
submitSucceeded?: booleanWhen true the FieldSubscriber will be notified of changes to the
submitSucceeded value in FieldState.
valid?: booleanWhen true the FieldSubscriber will be notified of changes to the valid
value in FieldState.
validating?: booleanWhen true the FieldSubscriber will be notified of changes to the
validating value in FieldState.
values?: booleanWhen true the FieldSubscriber will be notified of changes to the values
value in FieldState.
FormApibatch: (fn: () => void) => void)Allows batch updates by silencing notifications while the fn is running.
Example:
form.batch(() => {
form.change('firstName', 'Erik') // listeners not notified
form.change('lastName', 'Rasmussen') // listeners not notified
}) // NOW all listeners notifiedblur: (name: string) => voidBlurs (marks inactive) the given field.
change: (name: string, value: ?any) => voidChanges the value of the given field.
focus: (name: string) => voidFocuses (marks active) the given field.
initialize: (values: Object) => voidInitializes 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.
getState: () => FormStateA way to request the current state of the form without subscribing.
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) => UnsubscribeSubscribes to changes to the form. The subscriber will only be called when
values specified in subscription change. A form can have many subscribers.
registerField: (name: string, subscriber: FieldSubscriber, subscription: FieldSubscription, validate?: (value: ?any, allValues: Object) => any | Promise<any>) => UnsubscribeRegisters 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: () => voidResets the values back to the initial values the form was initialized with. Or empties all the values if the form was not initialized.
FormStateactive?: stringThe name of the currently active field. undefined if none are active.
dirty?: booleantrue if the form values are different from the values it was initialized with.
false otherwise. Comparison is done with shallow-equals.
error?: anyThe whole-form error returned by a validation function under the FORM_ERROR
key.
invalid?: booleantrue if any of the fields or the form has a validation or submission error.
false otherwise.
initialValues?: ObjectThe values the form was initialized with. undefined if the form was never
initialized.
pristine?: booleantrue if the form values are the same as the initial values. false otherwise.
Comparison is done with shallow-equals.
submitting?: booleantrue if the form is currently being submitted asynchronously. false
otherwise.
submitFailed?: booleantrue if the form was submitted, but the submission failed with submission
errors. false otherwise.
submitSucceeded?: booleantrue if the form was successfully submitted. false otherwise.
submitError?: anyThe whole-form submission error returned by onSubmit under the FORM_ERROR
key.
valid?: booleantrue if neither the form nor any of its fields has a validation or submission
error. false otherwise.
validating?: booleantrue if the form is currently being validated asynchronously. false
otherwise.
values?: ObjectThe current values of the form.
FormSubscriber: (state: FormState) => voidFormSubscription: { [string]: boolean }FormSubscription is an object containing the following:
activeWhen true the FormSubscriber will be notified of changes to the active
value in FormState.
dirtyWhen true the FormSubscriber will be notified of changes to the dirty
value in FormState.
errorWhen true the FormSubscriber will be notified of changes to the error
value in FormState.
initialValuesWhen true the FormSubscriber will be notified of changes to the
initialValues value in FormState.
invalidWhen true the FormSubscriber will be notified of changes to the invalid
value in FormState.
pristineWhen true the FormSubscriber will be notified of changes to the pristine
value in FormState.
submittingWhen true the FormSubscriber will be notified of changes to the submitting
value in FormState.
submitFailedWhen true the FormSubscriber will be notified of changes to the
submitFailed value in FormState.
submitSucceededWhen true the FormSubscriber will be notified of changes to the
submitSucceeded value in FormState.
validWhen true the FormSubscriber will be notified of changes to the valid
value in FormState.
validatingWhen true the FormSubscriber will be notified of changes to the validating
value in FormState.
valuesWhen true the FormSubscriber will be notified of changes to the values
value in FormState.
Unsubscribe : () => voidUnsubscribes a listener.
A form state management system for React that uses