|
| 1 | +# API |
| 2 | + |
| 3 | +- [`useForm`](#useform) |
| 4 | +- [`useField`](#usefield) |
| 5 | +- [`splitFormProps](#splitformprops) |
| 6 | +- [`useFormContext`](#useformcontext) |
| 7 | + |
| 8 | +## `useForm` |
| 9 | + |
| 10 | +```js |
| 11 | +import { useForm } from 'react-form' |
| 12 | + |
| 13 | +const instance = useForm(options) |
| 14 | +``` |
| 15 | + |
| 16 | +### Form Options |
| 17 | + |
| 18 | +- `defaultValues: any` |
| 19 | + - Use defaultValues to set the default values state for the form. If this object ever changes, the state will be reset to the new object. Thus, its important to use React.useMemo to make this object only change when necessary |
| 20 | +- `onSubmit(values, instance) => Promise` |
| 21 | + - `onSubmit` is called when the form's Form element is submitted or when `instance.handleSubmit` is called. |
| 22 | + - `values` is the submitted values object for the form |
| 23 | + - `instance` is the latest version of the form instance (the same instance that is returned from `useForm`) |
| 24 | + - If the promise returned from this function resolves, `instance.isSubmitted` will be set to `true` |
| 25 | + - When the promise returned from this function settles, `instance.isSubmitting` will be set to `false` |
| 26 | +- `validate async (values, instance) => String | false | undefined` |
| 27 | + - `validate` is an asynchronous function that is called when the form becomes dirty and is given the opportunity to set/clear/update errors and/or manage general form state |
| 28 | + - `instance` is the latest version of the form instance (the same instance that is returned from `useForm`) |
| 29 | + - [See below](#form-validation) for more information on form validation |
| 30 | + - Field level validation is also available. [See `useField`](#useField) |
| 31 | +- `validatePristine: Bool` |
| 32 | + - If you want validation to run when instance.isDirty is false, you can set the `validatePristine` option to `true` |
| 33 | + |
| 34 | +### Form Instance |
| 35 | + |
| 36 | +An `object` with the following components, properties and methods: |
| 37 | + |
| 38 | +- `Form: ReactComponent<form>` |
| 39 | + - **Required** |
| 40 | + - This component is a ready-to-use wrapper around the html `form` element. |
| 41 | + - It will proxy any props you pass it, excluding `onSubmit`. |
| 42 | + - It properly supplies the form context to any `useField` instances inside it. |
| 43 | +- `values: any` |
| 44 | + - The current values for the entire form |
| 45 | +- `meta: Object` |
| 46 | + |
| 47 | + - `error: String | any` |
| 48 | + - If an error is returned by the form's `validation` function, or if it is set programmatically, it will be stored here. |
| 49 | + - `isSubmitting: Bool` |
| 50 | + - Will be set to `true` if the form is currently submitting |
| 51 | + - `isDirty: Bool` |
| 52 | + - Will be set to `true` if the form is dirty |
| 53 | + - `isSubmitted: Bool` |
| 54 | + - Will be set to `true` if the form has been submitted successfully |
| 55 | + - `submissionAttempts: Int` |
| 56 | + - Will be incremented, starting from `0`, every time a form submission is attempted |
| 57 | + - `isValid: Bool` |
| 58 | + - Will be set to `true` if `isDirty === true` and `isValid === true`, meaning that the form has been touched and there are no field-level or form-level errors |
| 59 | + - `fieldsAreValidating` |
| 60 | + - Will be `true` if there are any fields validating (`field.meta.isValidating`) |
| 61 | + - `fieldsAreValid` |
| 62 | + - Will be `true` if there are no fields with an error (`field.meta.error`) |
| 63 | + - `isValid` |
| 64 | + - Will be `true` if every field is valid and there is no form error (`instance.meta.allFieldsValid && !instance.meta.error`) |
| 65 | + - `canSubmit: Bool` |
| 66 | + - Will be `true` if the form is valid and not in the middle of a submission attempt (`instance.meta.isValid && !instance.meta.isSubmitting`) |
| 67 | + - This can be used to enable/disable a submit button for the form. |
| 68 | + - `...any` |
| 69 | + - Any other meta information can be stored here via the `field.setMeta` or `instance.setFieldMeta` functions |
| 70 | + |
| 71 | +- `formContext: FormInstance` |
| 72 | + - This can be used to manually link `useField` instances to a parent form. This is useful if `useField` is in the same block scope as `useForm`. |
| 73 | + - Simply pass `formContext` to `useField` like so: `useField(fieldName, { formContext })`. That field is now linked to the form that provided the `formContext`. |
| 74 | +- `debugForm: Bool` |
| 75 | + - If set to `true` the form instance will be serialized and rendered after the `Form` element returned by the instance |
| 76 | +- `reset() => void` |
| 77 | + - This function will reset the form's state, and set `instance.values` to the `defaultValues` option |
| 78 | +- `setMeta((updater(previousMeta: Object) => newMeta: Object) | newMeta: Object)` |
| 79 | + - Use this function to update the form's `meta` value. |
| 80 | + - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's `setState` callback style. |
| 81 | + - Unlike React's setState pattern though, if a new object is passed, it will **NOT** replace the meta object entirely. Since this is a common use case, it will be shallowly merged. If you need to replace the entire meta object, please use the functional callback style above. |
| 82 | +- `handleSubmit(formSubmitEvent) => void` |
| 83 | + - This function is used to submit the form. |
| 84 | + - It is automatically called when using the `Form` component returned by `useTable`. |
| 85 | + - If you build your form using your own `form` element, this function is required and should be set as the callback to the `form` via the `onSubmit` prop |
| 86 | +- `debounce(Function, wait: Int) => Promise` |
| 87 | + - This function can be used to debounce any function at the specified wait time. Calls to this function will be deduped per form-instance. |
| 88 | + - Typically, this function is used in the `validate` callback to control validation timing and flow |
| 89 | + - A new promise is returned for each call to this function |
| 90 | + - Over the course of multiple overlapping calls to this function, only the latest active promise that both fires and finishes will actually resolve or reject. In other words, if you call this function before a previous call to it resolves, all previous calls will be discarded and never resolve or reject so as to avoid unwanted side effects from stale promises. Turns out this is easier than cancelling promises :) |
| 91 | +- `setValues(updater(previousValues: Object) => newValues: Object) | newValues: Object` |
| 92 | + - Use this function to update the form's `meta` value. |
| 93 | + - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's `setState` callback style. |
| 94 | + - If a value is passed, it **will replace the entire values** object, similar to React's `setState` callback style. |
| 95 | +- `runValidation() => void` |
| 96 | + - Use this function to manually run the form-level validation. |
| 97 | + - This function does not run validation for fields. If that is a requirement you have, the please file a feature request and I'll make it happen. |
| 98 | +- `getFieldValue(fieldPath: String) => any` |
| 99 | + - This function returns the `value` from the form's `instance.values` object located at the `fieldPath` string that was passed. |
| 100 | + - `fieldPath` is a string that supports object notation, eg. `foo[3].bar[1].baz` |
| 101 | +- `getFieldMeta(fieldPath: String) => Object: { error: String | null, ...any }` |
| 102 | + - This function returns a field's `meta` object from the form. |
| 103 | + - `fieldPath` is a string that supports object notation, eg. `foo[3].bar[1].baz` |
| 104 | +- `setFieldValue(fieldPath: String, (updater(previousValue: any) => newValue: any) | newValue: any, options: Object { isTouched: Bool } )` |
| 105 | + - Use this function to update a field's corresponding `value` that is stored in the `instance.values` object. |
| 106 | + - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's `setState` callback style. |
| 107 | + - Unlike React's setState pattern though, if a new object is passed, it will **NOT** replace the meta object entirely. Since this is a common use case, it will be shallowly merged. If you need to replace the entire meta object, please use the functional callback style above. |
| 108 | + - Optionally, an `options` object can be passed. |
| 109 | + - `isTouched: Bool` |
| 110 | + - Defaults to `true` |
| 111 | + - If set to `false`, this operation will not trigger the field's `isTouched` to automatically be set to `true` |
| 112 | +- `setFieldMeta(fieldPath: String, (updater(previousMeta: Object) => newMeta: Object) | newMeta: Object)` |
| 113 | + - Use this function to update a fields `meta` value. |
| 114 | + - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's `setState` callback style. |
| 115 | + - Unlike React's setState pattern though, if a new object is passed, it will **NOT** replace the meta object entirely. Since this is a common use case, it will be shallowly merged. If you need to replace the entire meta object, please use the functional callback style above. |
| 116 | +- `pushFieldValue(fieldPath: String, newValue: any)` |
| 117 | + - Use this function to push a new value into a field that has an array-like value. |
| 118 | + - An error will be thrown if the field's current value is not an array. |
| 119 | +- `insertFieldValue(fieldPath: String, insertIndex: Int, value: any)` |
| 120 | + - Use this function to insert a new value into a field that has an array-like value at the specified index. |
| 121 | + - An error will be thrown if the field's current value is not an array. |
| 122 | +- `removeFieldValue(fieldPath: String, removalIndex: Int)` |
| 123 | + - Use this function to remove a value from a field that has an array-like value at the specified index. |
| 124 | + - An error will be thrown if the field's current value is not an array. |
| 125 | +- `swapFieldValues(fieldPath: String, firstIndex: Int, secondIndex: Int)` |
| 126 | + - Use this function to swap two values inside of a field that has an array-like value at the specified indices. |
| 127 | + - An error will be thrown if the field's current value is not an array. |
| 128 | + |
| 129 | +## `useField` |
| 130 | + |
| 131 | +```js |
| 132 | +import { useField } from 'react-form' |
| 133 | + |
| 134 | +const fieldInstance = useField(fieldPath, options) |
| 135 | +``` |
| 136 | + |
| 137 | +### Field Options |
| 138 | + |
| 139 | +- `fieldPath: String` |
| 140 | + - **Required** |
| 141 | + - The path the value for this field. |
| 142 | + - Supports deeply nested object notation, eg. `foo[3].bar[1].baz` |
| 143 | + - Any integers that can be reliably detected between notation boundaries will be treated as array indices: `1`, `[1]`, `1.`, `.1.` or `.1` |
| 144 | +- `options` - An optional object to configure the field |
| 145 | + - `defaultValue: any` |
| 146 | + - Use `defaultValue` to set the default `value` state for the field. |
| 147 | + - If this object ever changes, the field meta will be reset to the new value. Thus, its important to use `React.useMemo` to make this object only change when necessary |
| 148 | + - `defaultError: String | undefined` |
| 149 | + - Use `defaultError` to set the default `error` state for the field. |
| 150 | + - If this object ever changes, the field meta will be reset to the new value. Thus, its important to use `React.useMemo` to make this object only change when necessary |
| 151 | + - `defaultIsTouched: Bool | undefined` |
| 152 | + - Use `defaultIsTouched` to set the default `isTouched` state for the field. |
| 153 | + - If this object ever changes, the field meta will be reset to the new value. Thus, its important to use `React.useMemo` to make this object only change when necessary |
| 154 | + - `defaultMeta: Object | undefined` |
| 155 | + - Use `defaultMeta` to set any additional default `meta` state for the field. |
| 156 | + - Unlike `defaultValue`, `defaultError` and `defaultIsTouched`, changing this object will not trigger the field meta to be updated. It is only updated when the `useField` hook mounts and `meta` for that field has not yet been initialized (`meta === undefined`) |
| 157 | + - `validate async (value, instance) => String | false | undefined` |
| 158 | + - `validate` is an asynchronous function that is called when the field becomes dirty and is given the opportunity to set/clear/update errors and/or manage general field meta |
| 159 | + - `instance` is the latest version of the field instance (the same instance that is returned from `useField`) |
| 160 | + - [See below](#validation) for more information on field validation |
| 161 | + - Form level validation is also available. [See `useForm`](#useform) |
| 162 | + - `filterValue: (value, instance) => newValue` |
| 163 | + - The `filterValue` function is used to manipulate new values before they are set via `field.setValue` and `instance.setFieldValue`. |
| 164 | + - This is useful for restricting fields to specific values, eg. min/max, length, regex replacement, disallowing invalid values (as opposed to warning about them), among limitless others. |
| 165 | + - `validatePristine: Bool` |
| 166 | + - If you want validation to run when instance.isDirty is false, you can set the `validatePristine` option to `true` |
| 167 | + |
| 168 | +### Field Instance |
| 169 | + |
| 170 | +An `object` with the following components, properties and methods: |
| 171 | + |
| 172 | +- `form: FormInstance` |
| 173 | + - The root form `instance` |
| 174 | +- `fieldName: String` |
| 175 | + - The full fieldName (from the root of the form) for this field |
| 176 | +- `value: any` |
| 177 | + - The current value of this field |
| 178 | +- `meta: Object {}` |
| 179 | + - `error: String | any` |
| 180 | + - If an error is returned by the field's `validation` function, or if it is set programmatically, it will be stored here. |
| 181 | + - `isTouched: Bool` |
| 182 | + - Will be set to `true` if the field has been touched. |
| 183 | + - `...any` |
| 184 | + - Any other meta information can be stored here via the `field.setMeta` or `instance.setFieldMeta` functions |
| 185 | +- `FieldScope: ReactComponent<Provider>` |
| 186 | + - Optional |
| 187 | + - This component does not render any markup |
| 188 | + - It set the new base field scope to this field's `fieldpath` |
| 189 | + - It supplies this new base field scope, along with the form scope to any `useField` instances inside it. |
| 190 | + - Any `useField(fieldPath)` instances used insde of `FieldScope` will inherit this field's `fieldPath` as a parent. |
| 191 | + - See [Field Scoping](#field-scoping) for more information |
| 192 | +- `debounce(Function, wait: Int) => Promise` |
| 193 | + - This function can be used to debounce any function at the specified wait time. Calls to this function will be deduped per `useField` instance. |
| 194 | + - Typically, this function is used in the `validate` callback to control validation timing and flow |
| 195 | + - A new promise is returned for each call to this function |
| 196 | + - Over the course of multiple overlapping calls to this function, only the latest active promise that both fires and finishes will actually resolve or reject. In other words, if you call this function before a previous call to it resolves, all previous calls will be discarded and never resolve or reject so as to avoid unwanted side effects from stale promises. Turns out this is easier than cancelling promises :) |
| 197 | +- `runValidation() => void` |
| 198 | + - Use this function to manually run this field's validation. |
| 199 | + - This function does not run validation for fields. |
| 200 | + |
| 201 | +#### Field-Specific Methods |
| 202 | + |
| 203 | +The following methods do not require the use of a `fieldPath`. This field's `fieldPath` will automatically be used. |
| 204 | + |
| 205 | +- `setValue((updater(previousValue: any) => newValue: any) | newValue: any, options: Object { isTouched: Bool } )` |
| 206 | + - Use this function to update a field's corresponding `value` that is stored in the `instance.values` object. |
| 207 | + - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's `setState` callback style. |
| 208 | + - Unlike React's setState pattern though, if a new object is passed, it will **NOT** replace the meta object entirely. Since this is a common use case, it will be shallowly merged. If you need to replace the entire meta object, please use the functional callback style above. |
| 209 | + - Optionally, an `options` object can be passed. |
| 210 | + - `isTouched: Bool` |
| 211 | + - Defaults to `true` |
| 212 | + - If set to `false`, this operation will not trigger the field's `isTouched` to automatically be set to `true` |
| 213 | +- `setMeta((updater(previousMeta: Object) => newMeta: Object) | newMeta: Object)` |
| 214 | + - Use this function to update a fields `meta` value. |
| 215 | + - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's `setState` callback style. |
| 216 | + - Unlike React's setState pattern though, if a new object is passed, it will **NOT** replace the meta object entirely. Since this is a common use case, it will be shallowly merged. If you need to replace the entire meta object, please use the functional callback style above. |
| 217 | +- `pushValue(newValue: any)` |
| 218 | + - Use this function to push a new value into a field that has an array-like value. |
| 219 | + - An error will be thrown if the field's current value is not an array. |
| 220 | +- `insertValue(insertIndex: Int, value: any)` |
| 221 | + - Use this function to insert a new value into a field that has an array-like value at the specified index. |
| 222 | + - An error will be thrown if the field's current value is not an array. |
| 223 | +- `removeValue(removalIndex: Int)` |
| 224 | + - Use this function to remove a value from a field that has an array-like value at the specified index. |
| 225 | + - An error will be thrown if the field's current value is not an array. |
| 226 | +- `swapValues(firstIndex: Int, secondIndex: Int)` |
| 227 | + |
| 228 | + - Use this function to swap two values inside of a field that has an array-like value at the specified indices. |
| 229 | + - An error will be thrown if the field's current value is not an array. |
| 230 | + |
| 231 | +#### Field-Scope Specific Methods |
| 232 | + |
| 233 | +The following methods are almost exactly the same as their top-level form `instance` counterparts, except for any `fieldPath` that is passed to them will be prefixed with this field's `fieldPath` |
| 234 | + |
| 235 | +For example, if our field had the `fieldPath` of `foo`, then `setFieldValue('[0]', true)` would be similar to calling `instance.setFieldValue('foo[0]', true)` |
| 236 | + |
| 237 | +- `setFieldValue(subFieldPath, ...)` - [See Form Instance](#form-instance) |
| 238 | +- `setFieldMeta(subFieldPath, ...)` - [See Form Instance](#form-instance) |
| 239 | +- `pushFieldValue(subFieldPath, ...)` - [See Form Instance](#form-instance) |
| 240 | +- `insertFieldValue(subFieldPath, ...)` - [See Form Instance](#form-instance) |
| 241 | +- `removeFieldValue(subFieldPath, ...)` - [See Form Instance](#form-instance) |
| 242 | +- `swapFieldValues(subFieldPath, ...)` - [See Form Instance](#form-instance) |
| 243 | + |
| 244 | +#### Using `useField` in the same scope as `useForm` |
| 245 | + |
| 246 | +If you get into a situation where you need to use `useForm` and `useField` in the same block scope, you may see a missing form context error. This is because your `useField` usage is not inside of a `<Form>` component. To get around this error for this use case, you can pass the form's `instance.formContext` value to the `useField` options to manually link them together: |
| 247 | + |
| 248 | +```js |
| 249 | +function App() { |
| 250 | + const { Form, formContext } = useForm() |
| 251 | + |
| 252 | + // This field will now be manually linked to the form above |
| 253 | + const fieldInstance = useField('age', { |
| 254 | + formContext, |
| 255 | + }) |
| 256 | + |
| 257 | + return <Form>...</Form> |
| 258 | +} |
| 259 | +``` |
| 260 | + |
| 261 | +## `splitFormProps` |
| 262 | + |
| 263 | +A utility function for filter React-Form-related props from an object. |
| 264 | + |
| 265 | +```js |
| 266 | +import { splitFormProps } from 'react-form' |
| 267 | + |
| 268 | +function TextField(props) { |
| 269 | + const [field, options, rest] = splitFormProps(props) |
| 270 | + |
| 271 | + // options === { |
| 272 | + // defaultValue, |
| 273 | + // defaultIsTouched, |
| 274 | + // defaultError, |
| 275 | + // defaultMeta, |
| 276 | + // validatePristine, |
| 277 | + // validate, |
| 278 | + // onSubmit, |
| 279 | + // defaultValues, |
| 280 | + // debugForm, |
| 281 | + // } |
| 282 | + |
| 283 | + const fieldInstance = useField(field, options) |
| 284 | + |
| 285 | + return <input {...rest} /> |
| 286 | +} |
| 287 | +``` |
| 288 | + |
| 289 | +## `useFormContext` |
| 290 | + |
| 291 | +A hook for gaining access to the form state from within a `Form` component |
| 292 | + |
| 293 | +```js |
| 294 | +import { useFormContext } from 'react-form' |
| 295 | + |
| 296 | +function App() { |
| 297 | + const { Form } = useForm() |
| 298 | + |
| 299 | + return ( |
| 300 | + <Form> |
| 301 | + <Stuff /> |
| 302 | + </Form> |
| 303 | + ) |
| 304 | +} |
| 305 | + |
| 306 | +function Stuff() { |
| 307 | + const formInstance = useFormContext() |
| 308 | + |
| 309 | + console.log(formInstance) |
| 310 | +} |
| 311 | +``` |
0 commit comments