├── .babelrc ├── .editorconfig ├── .eslintrc ├── .gitignore ├── .prettierrc ├── .travis.yml ├── LICENSE ├── README.md ├── jest.setup.js ├── logo └── logo.svg ├── package.json ├── rollup.config.js ├── src ├── constants.js ├── index.d.ts ├── index.js ├── parseInputArgs.js ├── useFormState.js ├── useInputId.js ├── useState.js ├── utils-hooks.js └── utils.js ├── test ├── test-utils.js ├── types.tsx ├── useFormState-formOptions.test.js ├── useFormState-ids.test.js ├── useFormState-input.test.js ├── useFormState-manual-updates.test.js ├── useFormState-pristine.test.js ├── useFormState-validation.test.js └── useFormState.test.js ├── tsconfig.json └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "test": { 4 | "presets": ["@babel/preset-env", "@babel/react"], 5 | "plugins": ["@babel/plugin-transform-runtime"] 6 | } 7 | }, 8 | "presets": [ 9 | [ 10 | "@babel/preset-env", 11 | { 12 | "modules": false, 13 | "exclude": ["transform-typeof-symbol"] 14 | } 15 | ] 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "@wsmd/eslint-config/typescript", 4 | "@wsmd/eslint-config/react", 5 | "@wsmd/eslint-config/prettier", 6 | "@wsmd/eslint-config/jest" 7 | ], 8 | "globals": { 9 | "__DEV__": false 10 | }, 11 | "rules": { 12 | "getter-return": "off", 13 | "consistent-return": "off", 14 | "@typescript-eslint/no-explicit-any": "off", 15 | "no-console": ["error", { "allow": ["warn", "error"] }], 16 | "no-underscore-dangle": ["error", { "allow": ["__DEV__"] }] 17 | }, 18 | "overrides": [ 19 | { 20 | "files": ["**/*.js"], 21 | "parser": "babel-eslint" 22 | }, 23 | { 24 | "files": ["test/**/*.js"], 25 | "rules": { 26 | "react/jsx-props-no-spreading": "off", 27 | "react/jsx-filename-extension": "off", 28 | "jsx-a11y/control-has-associated-label": "off" 29 | } 30 | } 31 | ], 32 | "ignorePatterns": ["test/types.tsx", "rollup.config.js"] 33 | } 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dev 2 | dist 3 | node_modules 4 | .DS_Store 5 | .npmrc 6 | *.log 7 | coverage 8 | package-lock.json 9 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "all", 3 | "singleQuote": true, 4 | "overrides": [ 5 | { 6 | "files": ["src/index.d.ts"], 7 | "options": { 8 | "printWidth": 100 9 | } 10 | } 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - node 5 | cache: 6 | yarn: true 7 | directories: 8 | - node_modules 9 | script: 10 | - yarn run prepublishOnly 11 | after_success: 12 | - yarn run coveralls 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Waseem Dahman 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |
4 | react-use-form-state 5 |

6 | 7 |

8 | 9 | Current Release 10 | 11 | 12 | Downloads 13 | 14 | 15 | CI Build 16 | 17 | 18 | Coverage Status 19 | 20 | 21 | Licence 22 | 23 |

24 | 25 |
26 | 📖 Table of Contents 27 |

28 | 29 | - [Motivation](#motivation) 30 | - [Getting Started](#getting-started) 31 | - [Examples](#examples) 32 | - [Basic Usage](#basic-usage) 33 | - [Initial State](#initial-state) 34 | - [Global Handlers](#global-handlers) 35 | - [Advanced Input Options](#advanced-input-options) 36 | - [Custom Input Validation](#custom-input-validation) 37 | - [Check If the Form State Is Pristine](#check-if-the-form-state-is-pristine) 38 | - [Without Using a `

` Element](#without-using-a-form--element) 39 | - [Labels](#labels) 40 | - [Custom Controls](#custom-controls) 41 | - [Updating Fields Manually](#updating-fields-manually) 42 | - [Resetting The Form State](#resetting-the-form-state) 43 | - [Working with TypeScript](#working-with-typescript) 44 | - [API](#api) 45 | - [`initialState`](#initialstate) 46 | - [`formOptions`](#formoptions) 47 | - [`formOptions.onBlur`](#formoptionsonblur) 48 | - [`formOptions.onChange`](#formoptionsonchange) 49 | - [`formOptions.onTouched`](#formoptionsontouched) 50 | - [`formOptions.onClear`](#formoptionsonclear) 51 | - [`formOptions.onReset`](#formoptionsonreset) 52 | - [`formOptions.validateOnBlur`](#formoptionsvalidateonblur) 53 | - [`formOptions.withIds`](#formoptionswithids) 54 | - [`[formState, inputs]`](#formstate-inputs) 55 | - [Form State](#form-state) 56 | - [Input Types](#input-types) 57 | - [Input Options](#input-options) 58 | - [License](#license) 59 | 60 |

61 |
62 | 63 | ## Motivation 64 | 65 | Managing form state in React can be a bit unwieldy sometimes. There are [plenty of great solutions](https://www.npmjs.com/search?q=react%20forms&ranking=popularity) already available that make managing forms state a breeze. However, many of those solutions are opinionated, packed with tons of features that may end up not being used, and/or require shipping a few extra bytes! 66 | 67 | Luckily, the recent introduction of [React Hooks](https://reactjs.org/docs/hooks-intro.html) and the ability to write custom hooks have enabled new possibilities when it comes sharing state logic. Form state is no exception! 68 | 69 | `react-use-form-state` is a small React Hook that attempts to [simplify managing form state](#examples), using the native form input elements you are familiar with! 70 | 71 | ## Getting Started 72 | 73 | To get it started, add `react-use-form-state` to your project: 74 | 75 | ``` 76 | npm install --save react-use-form-state 77 | ``` 78 | 79 | Please note that `react-use-form-state` requires `react@^16.8.0` as a peer dependency. 80 | 81 | ## Examples 82 | 83 | ### Basic Usage 84 | 85 | ```jsx 86 | import { useFormState } from 'react-use-form-state'; 87 | 88 | export default function SignUpForm({ onSubmit }) { 89 | const [formState, { text, email, password, radio }] = useFormState(); 90 | 91 | function handleSubmit(e) { 92 | // ... 93 | } 94 | 95 | return ( 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | ); 104 | } 105 | ``` 106 | 107 | From the example above, as the user fills in the form, the `formState` object will look something like this: 108 | 109 | ```js 110 | { 111 | values: { 112 | name: 'Mary Poppins', 113 | email: 'mary@example.com', 114 | password: '1234', 115 | plan: 'free', 116 | }, 117 | touched: { 118 | name: true, 119 | email: true, 120 | password: true, 121 | plan: true, 122 | }, 123 | validity: { 124 | name: true, 125 | email: true, 126 | password: false, 127 | plan: true, 128 | }, 129 | errors: { 130 | password: 'Please lengthen this text to 8 characters or more', 131 | }, 132 | clear: Function, 133 | clearField: Function, 134 | reset: Function, 135 | resetField: Function, 136 | setField: Function, 137 | } 138 | ``` 139 | 140 | ### Initial State 141 | 142 | `useFormState` takes an initial state object with keys matching the names of the inputs. 143 | 144 | ```jsx 145 | export default function RentCarForm() { 146 | const [formState, { checkbox, radio, select }] = useFormState({ 147 | trip: 'roundtrip', 148 | type: ['sedan', 'suv', 'van'], 149 | }); 150 | return ( 151 |
152 | 156 | 157 | 158 | 159 | 160 |
161 | ); 162 | } 163 | ``` 164 | 165 | ### Global Handlers 166 | 167 | `useFormState` supports [a variety of form-level event handlers](#formoptions) that you could use to perform certain actions: 168 | 169 | ```jsx 170 | export default function RentCarForm() { 171 | const [formState, { email, password }] = useFormState(null, { 172 | onChange(e, stateValues, nextStateValues) { 173 | const { name, value } = e.target; 174 | console.log(`the ${name} input has changed!`); 175 | }, 176 | }); 177 | return ( 178 | <> 179 | 180 | 181 | 182 | ); 183 | } 184 | ``` 185 | 186 | ### Advanced Input Options 187 | 188 | `useFormState` provides a quick and simple API to get started with building a form and managing its state. It also supports [HTML5 form validation](https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation) out of the box. 189 | 190 | ```jsx 191 | 192 | ``` 193 | 194 | While this covers that majority of validation cases, there are times when you need to attach custom event handlers or perform custom validation. 195 | 196 | For this, all [input functions](#input-types) provide an alternate API that allows you attach input-level event handlers such as `onChange` and `onBlur`, as well as providing custom validation logic. 197 | 198 | ```jsx 199 | export default function SignUpForm() { 200 | const [state, { text, password }] = useFormState(); 201 | return ( 202 | <> 203 | 204 | console.log('password input changed!'), 208 | onBlur: e => console.log('password input lost focus!'), 209 | validate: (value, values, e) => validatePassword(value), 210 | validateOnBlur: true, 211 | })} 212 | /> 213 | 214 | ); 215 | } 216 | ``` 217 | 218 | ### Custom Input Validation 219 | 220 | The example above [demonstrates](#advanced-input-options) how you can determine the validity of an input by passing a `validate()` method. You can also specify custom validation errors using the same method. 221 | 222 | The input is considered **valid** if this method returns `true` or `undefined`. 223 | 224 | Any [truthy value](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) other than `true` returned from this method will make the input **invalid**. This returned value is used as a **custom validation error** that can be retrieved from [`state.errors`](#form-state). 225 | 226 | For convenience, empty collection values such as empty objects, empty arrays, empty maps, empty sets are not considered invalidation errors, and if returned the input will be valid. 227 | 228 | ```jsx 229 | { 235 | if (!value.trim()) { 236 | return 'Password is required'; 237 | } 238 | if (!STRONG_PASSWORD_REGEX.test(value)) { 239 | return 'Password is not strong enough'; 240 | } 241 | }, 242 | })} 243 | /> 244 | ``` 245 | 246 | If the input's value is invalid based on the rules specified above, the form state will look similar to this: 247 | 248 | ```js 249 | { 250 | validity: { 251 | password: false, 252 | }, 253 | errors: { 254 | password: 'Password is not strong enough', 255 | } 256 | } 257 | ``` 258 | 259 | If the `validate()` method is not specified, `useFormState` will fallback to the HTML5 constraints validation to determine the validity of the input along with the appropriate error message. 260 | 261 | ### Check If the Form State Is Pristine 262 | 263 | `useFormState` exposes a `pristine` object, and an `isPristine()` helper via `formState` that you can use to check if the user has made any changes. 264 | 265 | This can be used for a Submit button, to disable it, if there are no actual changes to the form state: 266 | 267 | ```js 268 | function PristineForm() { 269 | const [formState, { text, password }] = useFormState(); 270 | return ( 271 |
272 | 273 | 274 | 277 |
278 | ); 279 | } 280 | ``` 281 | 282 | Checking if a field is pristine is done with simple equality `===`, with some exceptions. This can be overridden per field by providing a custom `compare` function. 283 | 284 | Note that a `compare` function is **required** for [`raw`](#custom-controls) inputs, otherwise, if not specified, the `pristine` value of a `raw` input will always be set to `false` after a change. 285 | 286 | ```jsx 287 | 296 | ``` 297 | 298 | ### Without Using a `
` Element 299 | 300 | `useFormState` is not limited to actual forms. It can be used anywhere inputs are used. 301 | 302 | ```jsx 303 | function LoginForm({ onSubmit }) { 304 | const [formState, { email, password }] = useFormState(); 305 | return ( 306 |
307 | 308 | 309 | 310 |
311 | ); 312 | } 313 | ``` 314 | 315 | ### Labels 316 | 317 | As a convenience, `useFormState` provides an optional API that helps with pairing a label to a specific input. 318 | 319 | When [`formOptions.withIds`](#formoptionswithids) is enabled, a label can be paired to an [input](#input-types) by using `input.label()`. This will populate the label's `htmlFor` attribute for an input with the same parameters. 320 | 321 | ```js 322 | const [formState, { label, text, radio }] = useFormState(initialState, { 323 | withIds: true, // enable automatic creation of id and htmlFor props 324 | }); 325 | 326 | return ( 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 |
337 | ); 338 | ``` 339 | 340 | Note that this will override any existing `id` prop if specified before calling the input functions. If you want the `id` to take precedence, it must be passed _after_ calling the input types like this: 341 | 342 | ```jsx 343 | 344 | ``` 345 | 346 | ### Custom Controls 347 | 348 | `useFormState` provides a `raw` type for working with controls that do not use React's [`SyntheticEvent`](https://reactjs.org/docs/events.html) system. For example, controls like [react-select](https://react-select.com/home) or [react-datepicker](https://www.npmjs.com/package/react-datepicker) have `onChange` and `value` props that expect a custom value instead of an event. 349 | 350 | To use this, your custom component should support an `onChange()` event which takes the value as a parameter, and a `value` prop which is expected to contain the value. Note that if no initial value is given, the component will receive a `value` prop of an empty string, which might not be what you want. Therefore, you must provide an [initial value](#initial-state) for `raw()` inputs when working with custom controls. 351 | 352 | ```js 353 | import DatePicker from 'react-datepicker'; 354 | 355 | function Widget() { 356 | const [formState, { raw }] = useFormState({ date: new Date() }); 357 | return ( 358 | <> 359 | 360 | 361 | ); 362 | } 363 | ``` 364 | 365 | You can also provide an `onChange` option with a return value in order to map the value passed from the custom control's `onChange` to a different value in the form state. 366 | 367 | ```js 368 | function Widget() { 369 | const [formState, { raw }] = useFormState({ date: new Date() }); 370 | return ( 371 | <> 372 | date.toString(); 376 | })} 377 | value={new Date(formState.date)} 378 | /> 379 | 380 | ); 381 | } 382 | ``` 383 | 384 | Note that `onChange()` for a `raw` value _must_ return a value. 385 | 386 | Many raw components do not support `onBlur()` correctly. For these components, you can use `touchOnChange` to mark a field as touched when it changes instead of on blur: 387 | 388 | ```js 389 | function Widget() { 390 | const [formState, { raw }] = useFormState({ date: new Date() }); 391 | return ( 392 | <> 393 | 399 | 400 | ); 401 | } 402 | ``` 403 | 404 | ### Updating Fields Manually 405 | 406 | There are cases where you may want to update the value of an input manually without user interaction. To do so, the `formState.setField` method can be used. 407 | 408 | ```js 409 | function Form() { 410 | const [formState, { text }] = useFormState(); 411 | 412 | function setNameField() { 413 | // manually setting the value of the "name" input 414 | formState.setField('name', 'Mary Poppins'); 415 | } 416 | 417 | return ( 418 | <> 419 | 420 | 421 | 422 | ); 423 | } 424 | ``` 425 | 426 | Please note that when `formState.setField` is called, any existing errors that might have been set due to previous interactions from the user will be cleared, and both of the `validity` and the `touched` states of the input will be set to `true`. 427 | 428 | It's also possible to clear a single input's value or to reset it to its initial value, if provided, using `formState.clearField` and `formState.resetField` respectively. 429 | 430 | As a convenience you can also set the error value for a single input using `formState.setFieldError`. 431 | 432 | ### Resetting The Form State 433 | 434 | The form state can be cleared or reset back to its initial state if provided at any time using `formState.clear` and `formState.reset` respectively. 435 | 436 | ```js 437 | function Form() { 438 | const [formState, { text, email }] = useFormState({ 439 | email: 'hello@example.com', 440 | }); 441 | return ( 442 | <> 443 | 444 | 445 | 446 | 447 | 448 | 449 | ); 450 | } 451 | ``` 452 | 453 | ## Working with TypeScript 454 | 455 | When working with TypeScript, the compiler needs to know what values and inputs `useFormState` is expected to be working with. 456 | 457 | For this reason, `useFormState` accepts an optional type argument that defines the state of the form and its fields which you could use to enforce type safety. 458 | 459 | ```ts 460 | interface LoginFormFields { 461 | username: string; 462 | password: string; 463 | remember_me: boolean; 464 | } 465 | 466 | const [formState, { text }] = useFormState(); 467 | ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ 468 | // OK 469 | 470 | formState.values.username 471 | 472 | // Error 473 | formState.values.doesNotExist 474 | 475 | ``` 476 | 477 | By default, `useFormState` will use the type `any` for the form state and its inputs if no type argument is provided. Therefore, it is recommended that you provide one. 478 | 479 | By default, the `errors` property will contain strings. If you return complex error objects from custom validation, you can provide an error type: 480 | 481 | ```ts 482 | interface I18nError { 483 | en: string; 484 | fr: string; 485 | } 486 | 487 | interface LoginFormErrors { 488 | username?: string | I18nError; 489 | password?: string; 490 | } 491 | 492 | const [formState, { text }] = useFormState(); 493 | 494 | formState.errors.username; // Will be undefined, a string, or an I18nError. 495 | ``` 496 | 497 | ## API 498 | 499 | ```js 500 | import { useFormState } from 'react-use-form-state'; 501 | 502 | function FormComponent() 503 | const [formState, inputs] = useFormState(initialState, formOptions); 504 | return ( 505 | // ... 506 | ) 507 | } 508 | ``` 509 | 510 | ### `initialState` 511 | 512 | `useFormState` takes an optional initial state object with keys as the name property of the form inputs, and values as the initial values of those inputs (similar to `defaultValue`/`defaultChecked`). 513 | 514 | ### `formOptions` 515 | 516 | `useFormState` also accepts an optional form options object as a second argument with following properties: 517 | 518 | #### `formOptions.onBlur` 519 | 520 | A function that gets called upon any `blur` of the form's inputs. This functions provides access to the input's `blur` [`SyntheticEvent`](https://reactjs.org/docs/events.html) 521 | 522 | ```js 523 | const [formState, inputs] = useFormState(null, { 524 | onBlur(e) { 525 | // accessing the inputs target that triggered the blur event 526 | const { name, value, ...target } = e.target; 527 | }, 528 | }); 529 | ``` 530 | 531 | #### `formOptions.onChange` 532 | 533 | A function that gets triggered upon any `change` of the form's inputs, and before updating `formState`. 534 | 535 | This function gives you access to the input's `change` [`SyntheticEvent`](https://reactjs.org/docs/events.html), the current `formState`, the next state after the change is applied. 536 | 537 | ```js 538 | const [formState, inputs] = useFormState(null, { 539 | onChange(e, stateValues, nextStateValues) { 540 | // accessing the actual inputs target that triggered the change event 541 | const { name, value, ...target } = e.target; 542 | // the state values prior to applying the change 543 | formState.values === stateValues; // true 544 | // the state values after applying the change 545 | nextStateValues; 546 | // the state value of the input. See Input Types below for more information. 547 | nextStateValues[name]; 548 | }, 549 | }); 550 | ``` 551 | 552 | #### `formOptions.onTouched` 553 | 554 | A function that gets called after an input inside the form has lost focus, and is marked as touched. It will be called once throughout the component life cycle. This functions provides access to the input's `blur` [`SyntheticEvent`](https://reactjs.org/docs/events.html). 555 | 556 | ```js 557 | const [formState, inputs] = useFormState(null, { 558 | onTouched(e) { 559 | // accessing the inputs target that triggered the blur event 560 | const { name, value, ...target } = e.target; 561 | }, 562 | }); 563 | ``` 564 | 565 | #### `formOptions.onClear` 566 | 567 | A function that gets called after calling `formState.clear` indicating that all fields in the form state are cleared successfully. 568 | 569 | ```js 570 | const [formState, inputs] = useFormState(null, { 571 | onClear() { 572 | // form state was cleared successfully 573 | }, 574 | }); 575 | 576 | formState.clear(); // clearing the form state 577 | ``` 578 | 579 | #### `formOptions.onReset` 580 | 581 | A function that gets called after calling `formState.reset` indicating that all fields in the form state are set to their initial values. 582 | 583 | ```js 584 | const [formState, inputs] = useFormState(null, { 585 | onReset() { 586 | // form state was reset successfully 587 | }, 588 | }); 589 | formState.reset(); // resetting the form state 590 | ``` 591 | 592 | #### `formOptions.validateOnBlur` 593 | 594 | By default, input validation is performed on both of the `change` and the `blur` events. Setting `validateOnBlur` to `true` will limit input validation to be **only** performed on `blur` (when the input loses focus). When set to `false`, input validation will **only** be performed on `change`. 595 | 596 | #### `formOptions.withIds` 597 | 598 | Indicates whether `useFormState` should generate and pass an `id` attribute to its fields. This is helpful when [working with labels](#labels-and-ids). 599 | 600 | It can be one of the following: 601 | 602 | A `boolean` indicating whether [input types](#input-types) should pass an `id` attribute to the inputs (set to `false` by default). 603 | 604 | ```js 605 | const [formState, inputs] = useFormState(null, { 606 | withIds: true, 607 | }); 608 | ``` 609 | 610 | Or a custom id formatter: a function that gets called with the input's name and own value, and expected to return a unique string (using these parameters) that will be as the input id. 611 | 612 | ```js 613 | const [formState, inputs] = useFormState(null, { 614 | withIds: (name, ownValue) => 615 | ownValue ? `MyForm-${name}-${ownValue}` : `MyForm-${name}`, 616 | }); 617 | ``` 618 | 619 | Note that when `withIds` is set to `false`, applying `input.label()` will be a no-op. 620 | 621 | ### `[formState, inputs]` 622 | 623 | The return value of `useFormState`. An array of two items, the first is the [form state](#form-state), and the second an [input types](#input-types) object. 624 | 625 | #### Form State 626 | 627 | The first item returned by `useFormState`. 628 | 629 | ```js 630 | const [formState, inputs] = useFormState(); 631 | ``` 632 | 633 | An object containing the form state that updates during subsequent re-renders. It also include methods to update the form state manually. 634 | 635 | ```ts 636 | formState = { 637 | // an object holding the values of all input being rendered 638 | values: { 639 | [name: string]: string | string[] | boolean, 640 | }, 641 | 642 | // an object indicating whether the value of each input is valid 643 | validity: { 644 | [name: string]?: boolean, 645 | }, 646 | 647 | // an object holding all errors resulting from input validations 648 | errors: { 649 | [name: string]?: any, 650 | }, 651 | 652 | // an object indicating whether the input was touched (focused) by the user 653 | touched: { 654 | [name: string]?: boolean, 655 | }, 656 | 657 | // an object indicating whether the value of each input is pristine 658 | pristine: { 659 | [name: string]: boolean, 660 | }, 661 | 662 | // whether the form is pristine or not 663 | isPristine(): boolean, 664 | 665 | // clears all fields in the form 666 | clear(): void, 667 | 668 | // clears the state of an input 669 | clearField(name: string): void, 670 | 671 | // resets all fields the form back to their initial state if provided 672 | reset(): void, 673 | 674 | // resets the state of an input back to its initial state if provided 675 | resetField(name: string): void, 676 | 677 | // updates the value of an input 678 | setField(name: string, value: string): void, 679 | 680 | // sets the error of an input 681 | setFieldError(name: string, error: string): void, 682 | } 683 | ``` 684 | 685 | #### Input Types 686 | 687 | The second item returned by `useFormState`. 688 | 689 | ```js 690 | const [formState, input] = useFormState(); 691 | ``` 692 | 693 | An object with keys as input types. Each type is a function that returns the appropriate props that can be spread on the corresponding input. 694 | 695 | The following types are currently supported: 696 | 697 | | Type and Usage | State Shape | 698 | | --------------------------------------------------------------- | -------------------------------------------------------------------------- | 699 | | `` | `{ [name: string]: string }` | 700 | | `` | `{ [name: string]: string }` | 701 | | `` | `{ [name: string]: string }` | 702 | | `` | `{ [name: string]: string }` | 703 | | `` | `{ [name: string]: string }` | 704 | | `` | `{ [name: string]: string }` | 705 | | `` | `{ [name: string]: string }` | 706 | | `` | `{ [name: string]: string }` | 707 | | `` | `{ [name: string]: string }` | 708 | | `` | `{ [name: string]: string }` | 709 | | `` | `{ [name: string]: Array }` | 710 | | `` | `{ [name: string]: boolean }` | 711 | | `` | `{ [name: string]: string }` | 712 | | `` | `{ [name: string]: string }` | 713 | | `` | `{ [name: string]: string }` | 714 | | `` | `{ [name: string]: string }` | 715 | | `` | `{ [name: string]: Array }` | 717 | | `