├── src ├── index.js ├── parseInputArgs.js ├── utils-hooks.js ├── useInputId.js ├── constants.js ├── utils.js ├── useState.js ├── index.d.ts └── useFormState.js ├── .gitignore ├── .editorconfig ├── tsconfig.json ├── .prettierrc ├── .travis.yml ├── .babelrc ├── jest.setup.js ├── .eslintrc ├── LICENSE ├── logo └── logo.svg ├── rollup.config.js ├── test ├── test-utils.js ├── useFormState-formOptions.test.js ├── useFormState.test.js ├── useFormState-ids.test.js ├── useFormState-manual-updates.test.js ├── useFormState-pristine.test.js ├── useFormState-validation.test.js ├── types.tsx └── useFormState-input.test.js ├── package.json └── README.md /src/index.js: -------------------------------------------------------------------------------- 1 | export { default as useFormState } from './useFormState'; 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dev 2 | dist 3 | node_modules 4 | .DS_Store 5 | .npmrc 6 | *.log 7 | coverage 8 | package-lock.json 9 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "esModuleInterop": true, 5 | "lib": ["dom", "es2015"], 6 | "jsx": "react" 7 | }, 8 | "include": ["src", "test"] 9 | } 10 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /jest.setup.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-extraneous-dependencies */ 2 | 3 | import 'jest-dom/extend-expect'; 4 | import 'react-testing-library/cleanup-after-each'; 5 | 6 | /** 7 | * Mocking calls to console.warn to test against warnings and errors logged 8 | * in the development environment. 9 | */ 10 | let consoleSpy; 11 | beforeEach(() => { 12 | consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); 13 | global.__DEV__ = 'development'; 14 | }); 15 | afterEach(() => { 16 | consoleSpy.mockRestore(); 17 | global.__DEV__ = process.env.NODE_ENV; 18 | }); 19 | -------------------------------------------------------------------------------- /src/parseInputArgs.js: -------------------------------------------------------------------------------- 1 | import { identity, noop, toString } from './utils'; 2 | 3 | const defaultInputOptions = { 4 | onChange: identity, 5 | onBlur: noop, 6 | validate: null, 7 | validateOnBlur: undefined, 8 | touchOnChange: false, 9 | compare: null, 10 | }; 11 | 12 | export function parseInputArgs(args) { 13 | let name; 14 | let ownValue; 15 | let options; 16 | if (typeof args[0] === 'string' || typeof args[0] === 'number') { 17 | [name, ownValue] = args; 18 | } else { 19 | [{ name, value: ownValue, ...options }] = args; 20 | } 21 | 22 | ownValue = toString(ownValue); 23 | 24 | return { 25 | name, 26 | ownValue, 27 | hasOwnValue: !!ownValue, 28 | ...defaultInputOptions, 29 | ...options, 30 | }; 31 | } 32 | -------------------------------------------------------------------------------- /src/utils-hooks.js: -------------------------------------------------------------------------------- 1 | import { useRef } from 'react'; 2 | 3 | export function useMap() { 4 | const map = useRef(new Map()); 5 | return { 6 | set: (key, value) => map.current.set(key, value), 7 | has: key => map.current.has(key), 8 | get: key => map.current.get(key), 9 | }; 10 | } 11 | 12 | export function useReferencedCallback() { 13 | const callbacks = useMap(); 14 | return (key, current) => { 15 | if (!callbacks.has(key)) { 16 | const callback = (...args) => callback.current(...args); 17 | callbacks.set(key, callback); 18 | } 19 | callbacks.get(key).current = current; 20 | return callbacks.get(key); 21 | }; 22 | } 23 | 24 | export function useWarnOnce() { 25 | const didWarnRef = useRef(new Set()); 26 | return (key, message) => { 27 | if (!didWarnRef.current.has(key)) { 28 | didWarnRef.current.add(key); 29 | console.warn('[useFormState]', message); 30 | } 31 | }; 32 | } 33 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /src/useInputId.js: -------------------------------------------------------------------------------- 1 | import { useCallback } from 'react'; 2 | import { toString, noop, isFunction } from './utils'; 3 | 4 | const defaultCreateId = (name, value) => 5 | ['__ufs', name, value].filter(Boolean).join('__'); 6 | 7 | export function useInputId(implementation) { 8 | const getId = useCallback( 9 | (name, ownValue) => { 10 | let createId; 11 | if (!implementation) { 12 | createId = noop; 13 | } else if (isFunction(implementation)) { 14 | createId = implementation; 15 | } else { 16 | createId = defaultCreateId; 17 | } 18 | const value = toString(ownValue); 19 | return value ? createId(name, value) : createId(name); 20 | }, 21 | [implementation], 22 | ); 23 | 24 | const getIdProp = useCallback( 25 | (prop, name, value) => { 26 | const id = getId(name, value); 27 | return id === undefined ? {} : { [prop]: id }; 28 | }, 29 | [getId], 30 | ); 31 | 32 | return { getIdProp }; 33 | } 34 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/constants.js: -------------------------------------------------------------------------------- 1 | export const CHECKBOX = 'checkbox'; 2 | export const COLOR = 'color'; 3 | export const DATE = 'date'; 4 | export const EMAIL = 'email'; 5 | export const MONTH = 'month'; 6 | export const NUMBER = 'number'; 7 | export const PASSWORD = 'password'; 8 | export const RADIO = 'radio'; 9 | export const RANGE = 'range'; 10 | export const RAW = 'raw'; 11 | export const SEARCH = 'search'; 12 | export const SELECT = 'select'; 13 | export const SELECT_MULTIPLE = 'selectMultiple'; 14 | export const TEL = 'tel'; 15 | export const TEXT = 'text'; 16 | export const TEXTAREA = 'textarea'; 17 | export const TIME = 'time'; 18 | export const URL = 'url'; 19 | export const WEEK = 'week'; 20 | export const LABEL = 'label'; 21 | 22 | /** 23 | * @todo add support for datetime-local 24 | */ 25 | export const DATETIME_LOCAL = 'datetime-local'; 26 | 27 | export const INPUT_TYPES = [ 28 | CHECKBOX, 29 | COLOR, 30 | DATE, 31 | EMAIL, 32 | MONTH, 33 | NUMBER, 34 | PASSWORD, 35 | RADIO, 36 | RANGE, 37 | RAW, 38 | SEARCH, 39 | SELECT, 40 | SELECT_MULTIPLE, 41 | TEL, 42 | TEXT, 43 | TEXTAREA, 44 | TIME, 45 | URL, 46 | WEEK, 47 | ]; 48 | -------------------------------------------------------------------------------- /logo/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import babel from '@rollup/plugin-babel'; 3 | import replace from '@rollup/plugin-replace'; 4 | import pkg from './package.json'; 5 | 6 | const isDevBuild = process.env.BUILD === 'development'; 7 | 8 | export default { 9 | input: 'src/index.js', 10 | output: [ 11 | !isDevBuild && { 12 | file: pkg.main, 13 | format: 'cjs', 14 | }, 15 | { 16 | file: pkg.module, 17 | format: 'es', 18 | sourcemap: isDevBuild, 19 | }, 20 | ], 21 | external: Object.keys(pkg.peerDependencies), 22 | plugins: [ 23 | babel({ 24 | babelHelpers: 'bundled', 25 | }), 26 | replace({ 27 | __DEV__: "process.env.NODE_ENV === 'development'", 28 | }), 29 | copyFile('src/index.d.ts', 'dist/index.d.ts'), 30 | ], 31 | }; 32 | 33 | function copyFile(source, dest) { 34 | let called = false; 35 | return { 36 | async writeBundle() { 37 | if (called) return; 38 | called = true; 39 | try { 40 | await fs.promises.copyFile(source, dest); 41 | console.log(`copied ${source} → ${dest}`); 42 | } catch (err) { 43 | console.log(err); 44 | process.exit(1); 45 | } 46 | }, 47 | }; 48 | } 49 | -------------------------------------------------------------------------------- /test/test-utils.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, fireEvent } from 'react-testing-library'; 3 | import { useFormState } from '../src'; 4 | 5 | export { renderHook } from 'react-hooks-testing-library'; 6 | 7 | export { render as renderElement, fireEvent }; 8 | 9 | export const InputTypes = { 10 | textLike: ['text', 'email', 'password', 'search', 'tel', 'url'], 11 | time: ['date', 'month', 'time', 'week'], 12 | numeric: ['number', 'range'], 13 | }; 14 | 15 | export function renderWithFormState(renderFn, ...useFormStateArgs) { 16 | const formStateRef = { current: null }; 17 | 18 | const Wrapper = ({ children }) => { 19 | const [state, inputs] = useFormState(...useFormStateArgs); 20 | formStateRef.current = state; 21 | return children([state, inputs]); 22 | }; 23 | 24 | const { container } = render({renderFn}); 25 | 26 | const fire = (type, target, node = container.firstChild) => { 27 | fireEvent[type](node, { target }); 28 | }; 29 | 30 | return { 31 | blur: (...args) => fire('blur', ...args), 32 | change: (...args) => fire('change', ...args), 33 | click: (...args) => fire('click', ...args), 34 | formState: formStateRef, 35 | root: container.firstChild, 36 | }; 37 | } 38 | -------------------------------------------------------------------------------- /test/useFormState-formOptions.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { renderWithFormState } from './test-utils'; 3 | 4 | describe('useFormState options', () => { 5 | it('calls options.onChange when an input changes', async () => { 6 | const changeHandler = jest.fn(); 7 | const { change } = renderWithFormState( 8 | ([, { text }]) => , 9 | null, 10 | { onChange: changeHandler }, 11 | ); 12 | change({ value: 'w' }); 13 | expect(changeHandler).toHaveBeenCalledWith( 14 | expect.any(Object), // SyntheticEvent 15 | expect.objectContaining({ username: '' }), 16 | expect.objectContaining({ username: 'w' }), 17 | ); 18 | }); 19 | 20 | it('calls options.onBlur when an input changes', () => { 21 | const blurHandler = jest.fn(); 22 | const { blur } = renderWithFormState( 23 | ([, { text }]) => , 24 | null, 25 | { onBlur: blurHandler }, 26 | ); 27 | blur(); 28 | expect(blurHandler).toHaveBeenCalledWith(expect.any(Object)); 29 | blur(); 30 | expect(blurHandler).toHaveBeenCalledTimes(2); 31 | }); 32 | 33 | it('calls options.onTouched when an input changes', () => { 34 | const touchedHandler = jest.fn(); 35 | const { blur } = renderWithFormState( 36 | ([, { text }]) => , 37 | null, 38 | { onTouched: touchedHandler }, 39 | ); 40 | blur(); 41 | expect(touchedHandler).toHaveBeenCalled(); 42 | blur(); 43 | expect(touchedHandler).toHaveBeenCalledTimes(1); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /test/useFormState.test.js: -------------------------------------------------------------------------------- 1 | import { useFormState } from '../src'; 2 | import { renderHook, InputTypes } from './test-utils'; 3 | 4 | describe('useFormState API', () => { 5 | it('returns an array matching [formState, input]', () => { 6 | const { result } = renderHook(() => useFormState()); 7 | expect(result.current).toEqual([ 8 | { 9 | values: {}, 10 | validity: {}, 11 | touched: {}, 12 | errors: {}, 13 | pristine: {}, 14 | clear: expect.any(Function), 15 | reset: expect.any(Function), 16 | setField: expect.any(Function), 17 | setFieldError: expect.any(Function), 18 | clearField: expect.any(Function), 19 | resetField: expect.any(Function), 20 | isPristine: expect.any(Function), 21 | }, 22 | expect.any(Object), 23 | ]); 24 | }); 25 | 26 | it.each([ 27 | ...InputTypes.textLike, 28 | ...InputTypes.numeric, 29 | ...InputTypes.time, 30 | 'checkbox', 31 | 'color', 32 | 'radio', 33 | 'select', 34 | 'selectMultiple', 35 | 'textarea', 36 | 'label', 37 | ])('has a method for type "%s"', type => { 38 | const { result } = renderHook(() => useFormState()); 39 | const [, inputs] = result.current; 40 | expect(inputs[type]).toBeInstanceOf(Function); 41 | }); 42 | 43 | it('sets initial/default state for inputs', () => { 44 | const initialState = { 45 | name: 'Mary Poppins', 46 | email: 'user@example.com', 47 | options: ['foo', 'bar'], 48 | }; 49 | const { result } = renderHook(() => useFormState(initialState)); 50 | const [formState] = result.current; 51 | expect(formState.values).toEqual(expect.objectContaining(initialState)); 52 | }); 53 | 54 | it('persists reference to the formState object', () => { 55 | const firstRenderResult = { current: null }; 56 | const { result, rerender } = renderHook(() => useFormState()); 57 | [firstRenderResult.current] = result.current; 58 | rerender(); 59 | expect(result.current[0]).toBe(firstRenderResult.current); 60 | expect(result.current[0].setField).toBe(firstRenderResult.current.setField); 61 | }); 62 | }); 63 | -------------------------------------------------------------------------------- /src/utils.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Returns a function that can be called with an object. The return value of the 3 | * new function is a copy of the object excluding the key passed initially. 4 | */ 5 | export function omit(key) { 6 | return object => { 7 | const { [key]: toRemove, ...rest } = object; 8 | return rest; 9 | }; 10 | } 11 | 12 | /** 13 | * An empty function. It does nothing. 14 | */ 15 | export function noop() {} 16 | 17 | /** 18 | * Like `noop`, but passes through the first argument. 19 | */ 20 | export function identity(val) { 21 | return val; 22 | } 23 | 24 | /** 25 | * Cast non-string values to a string, with the exception of functions, symbols, 26 | * and undefined. 27 | */ 28 | export function toString(value) { 29 | switch (typeof value) { 30 | case 'function': 31 | case 'symbol': 32 | case 'undefined': 33 | return ''; 34 | default: 35 | return '' + value; // eslint-disable-line prefer-template 36 | } 37 | } 38 | 39 | export function isFunction(value) { 40 | return typeof value === 'function'; 41 | } 42 | 43 | const objectToString = value => Object.prototype.toString.call(value); 44 | 45 | /** 46 | * Determines if a value is an empty collection (object, array, string, map, set) 47 | * @note this returns false for anything else. 48 | */ 49 | export function isEmpty(value) { 50 | if (value == null) { 51 | return true; 52 | } 53 | if (Array.isArray(value) || typeof value === 'string') { 54 | return !value.length; 55 | } 56 | if ( 57 | objectToString(value) === '[object Map]' || 58 | objectToString(value) === '[object Set]' 59 | ) { 60 | return !value.size; 61 | } 62 | if (objectToString(value) === '[object Object]') { 63 | return !Object.keys(value).length; 64 | } 65 | return false; 66 | } 67 | 68 | export function isEqual(value, other) { 69 | if (Array.isArray(value) && Array.isArray(other)) { 70 | return ( 71 | value.length === other.length && 72 | value.every(a => other.indexOf(a) > -1) && 73 | other.every(b => value.indexOf(b) > -1) 74 | ); 75 | } 76 | return value === other; 77 | } 78 | 79 | export function testIsEqualCompatibility(value) { 80 | /* istanbul ignore if */ 81 | if (Array.isArray(value)) { 82 | return value.every(testIsEqualCompatibility); 83 | } 84 | return value == null || /^[sbn]/.test(typeof value); // basic primitives 85 | } 86 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-use-form-state", 3 | "version": "0.13.2", 4 | "description": "React hook for managing form and inputs state", 5 | "main": "dist/index.js", 6 | "module": "dist/index.es.js", 7 | "types": "dist/index.d.ts", 8 | "repository": "wsmd/react-use-form-state", 9 | "homepage": "http://react-use-form-state.now.sh", 10 | "bugs": { 11 | "url": "https://github.com/wsmd/react-use-form-state/issues" 12 | }, 13 | "author": "Waseem Dahman ", 14 | "license": "MIT", 15 | "keywords": [ 16 | "react", 17 | "form", 18 | "forms", 19 | "state", 20 | "hook" 21 | ], 22 | "scripts": { 23 | "build": "rollup -c", 24 | "build:dev": "rollup -c -w --environment=BUILD:development", 25 | "clean": "rm -rf dist", 26 | "coveralls": "cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js", 27 | "lint": "eslint src test", 28 | "prepack": "yarn clean && yarn build", 29 | "prepublishOnly": "yarn test:all", 30 | "test": "jest --coverage", 31 | "test:all": "yarn lint && yarn typecheck && yarn test", 32 | "typecheck": "tsc --noEmit" 33 | }, 34 | "files": [ 35 | "dist" 36 | ], 37 | "jest": { 38 | "watchPathIgnorePatterns": [ 39 | "dist" 40 | ], 41 | "collectCoverageFrom": [ 42 | "src/**.js" 43 | ], 44 | "coveragePathIgnorePatterns": [ 45 | "src/index.js" 46 | ], 47 | "setupFilesAfterEnv": [ 48 | "/jest.setup.js" 49 | ] 50 | }, 51 | "peerDependencies": { 52 | "react": "^16.8.0", 53 | "react-dom": "^16.8.0" 54 | }, 55 | "devDependencies": { 56 | "@babel/cli": "^7.1.2", 57 | "@babel/core": "^7.1.2", 58 | "@babel/plugin-transform-runtime": "^7.3.4", 59 | "@babel/preset-env": "^7.9.6", 60 | "@babel/preset-react": "^7.0.0", 61 | "@rollup/plugin-babel": "^5.0.0", 62 | "@rollup/plugin-replace": "^2.3.2", 63 | "@types/jest": "^24.0.11", 64 | "@types/react": "^16.8.4", 65 | "@wsmd/eslint-config": "^1.2.0", 66 | "babel-core": "^7.0.0-bridge.0", 67 | "babel-eslint": "^10.1.0", 68 | "babel-jest": "^23.6.0", 69 | "coveralls": "^3.0.9", 70 | "eslint": "^6.8.0", 71 | "jest": "^24.7.1", 72 | "jest-dom": "^2.1.0", 73 | "prettier": "^1.19.1", 74 | "react": "^16.13.1", 75 | "react-dom": "^16.13.1", 76 | "react-hooks-testing-library": "^0.3.7", 77 | "react-testing-library": "^6.0.0", 78 | "rollup": "^2.10.2", 79 | "typescript": "^3.7.4" 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/useState.js: -------------------------------------------------------------------------------- 1 | import { useReducer, useRef } from 'react'; 2 | import { isFunction, isEqual } from './utils'; 3 | import { useMap } from './utils-hooks'; 4 | 5 | function stateReducer(state, newState) { 6 | return isFunction(newState) ? newState(state) : { ...state, ...newState }; 7 | } 8 | 9 | export function useState({ initialState }) { 10 | const state = useRef(); 11 | const initialValues = useMap(); 12 | const comparators = useMap(); 13 | const [values, setValues] = useReducer(stateReducer, initialState || {}); 14 | const [touched, setTouched] = useReducer(stateReducer, {}); 15 | const [validity, setValidity] = useReducer(stateReducer, {}); 16 | const [errors, setError] = useReducer(stateReducer, {}); 17 | const [pristine, setPristine] = useReducer(stateReducer, {}); 18 | 19 | state.current = { values, touched, validity, errors, pristine }; 20 | 21 | function getInitialValue(name) { 22 | return initialValues.has(name) 23 | ? initialValues.get(name) 24 | : initialState[name]; 25 | } 26 | 27 | function updatePristine(name, value) { 28 | let comparator = comparators.get(name); 29 | // If comparator isn't available for an input, that means the input wasn't 30 | // mounted, or manually added via setField. 31 | comparator = isFunction(comparator) ? comparator : isEqual; 32 | setPristine({ [name]: !!comparator(getInitialValue(name), value) }); 33 | } 34 | 35 | function setFieldState(name, value, inputValidity, inputTouched, inputError) { 36 | setValues({ [name]: value }); 37 | setTouched({ [name]: inputTouched }); 38 | setValidity({ [name]: inputValidity }); 39 | setError({ [name]: inputError }); 40 | updatePristine(name, value); 41 | } 42 | 43 | function setField(name, value) { 44 | // need to store the initial value via setField in case it's before the 45 | // input of the given name is rendered. 46 | if (!initialValues.has(name)) { 47 | initialValues.set(name, value); 48 | } 49 | setFieldState(name, value, true, true); 50 | } 51 | 52 | function clearField(name) { 53 | setField(name); 54 | } 55 | 56 | function resetField(name) { 57 | setField(name, getInitialValue(name)); 58 | } 59 | 60 | function isPristine() { 61 | return Object.keys(state.current.pristine).every( 62 | key => !!state.current.pristine[key], 63 | ); 64 | } 65 | 66 | function forEach(cb) { 67 | Object.keys(state.current.values).forEach(cb); 68 | } 69 | 70 | return { 71 | get current() { 72 | return state.current; 73 | }, 74 | setValues, 75 | setTouched, 76 | setValidity, 77 | setError, 78 | setField, 79 | setPristine, 80 | updatePristine, 81 | initialValues, 82 | resetField, 83 | clearField, 84 | forEach, 85 | isPristine, 86 | comparators, 87 | }; 88 | } 89 | -------------------------------------------------------------------------------- /test/useFormState-ids.test.js: -------------------------------------------------------------------------------- 1 | import { useFormState } from '../src'; 2 | import { renderHook } from './test-utils'; 3 | 4 | describe('Input IDs', () => { 5 | /** 6 | * Label only needs a htmlFor 7 | */ 8 | it('input method correct props from type "label"', () => { 9 | const { result } = renderHook(() => useFormState(null, { withIds: true })); 10 | const [, input] = result.current; 11 | expect(input.label('name')).toEqual({ 12 | htmlFor: expect.any(String), 13 | }); 14 | }); 15 | 16 | it('input method has an "id" prop', () => { 17 | const { result } = renderHook(() => useFormState(null, { withIds: true })); 18 | const [, input] = result.current; 19 | expect(input.text('name')).toHaveProperty('id', expect.any(String)); 20 | }); 21 | 22 | it('generates unique IDs for inputs with different names', () => { 23 | const { result } = renderHook(() => useFormState(null, { withIds: true })); 24 | const [, input] = result.current; 25 | const { id: firstId } = input.text('firstName'); 26 | const { id: lastId } = input.text('lastName'); 27 | expect(firstId).not.toBe(lastId); 28 | }); 29 | 30 | it('generates unique IDs for inputs with the same name and different values', () => { 31 | const { result } = renderHook(() => useFormState(null, { withIds: true })); 32 | const [, input] = result.current; 33 | const { id: freeId } = input.radio('plan', 'free'); 34 | const { id: premiumId } = input.radio('plan', 'premium'); 35 | expect(freeId).not.toBe(premiumId); 36 | }); 37 | 38 | it('sets matching IDs for inputs and labels', () => { 39 | const { result } = renderHook(() => useFormState(null, { withIds: true })); 40 | const [, input] = result.current; 41 | const { id: inputId } = input.text('name'); 42 | const { htmlFor: labelId } = input.label('name'); 43 | expect(labelId).toBe(inputId); 44 | }); 45 | 46 | it('sets matching IDs for inputs and labels with non string values', () => { 47 | const { result } = renderHook(() => useFormState(null, { withIds: true })); 48 | const [, input] = result.current; 49 | const { id: inputId } = input.checkbox('name', 0); 50 | const { htmlFor: labelId } = input.label('name', 0); 51 | expect(labelId).toBe(inputId); 52 | }); 53 | 54 | it('sets a custom id when formOptions.withIds is set to a function', () => { 55 | const customInputFormat = jest.fn((name, value) => 56 | value ? `form-${name}-${value}` : `form-${name}`, 57 | ); 58 | const { result } = renderHook(() => 59 | useFormState(null, { withIds: customInputFormat }), 60 | ); 61 | const [, input] = result.current; 62 | 63 | // inputs with own values (e.g. radio button) 64 | 65 | const radioProps = input.radio('option', 0); 66 | expect(radioProps.id).toEqual('form-option-0'); 67 | expect(customInputFormat).toHaveBeenCalledWith('option', '0'); 68 | 69 | const radioLabelProps = input.label('option', 0); 70 | expect(radioLabelProps.htmlFor).toEqual('form-option-0'); 71 | expect(customInputFormat).toHaveBeenNthCalledWith(2, 'option', '0'); 72 | 73 | // inputs with no own values (e.g. text input) 74 | 75 | const textProps = input.text('name'); 76 | expect(textProps.id).toEqual('form-name'); 77 | expect(customInputFormat).toHaveBeenLastCalledWith('name'); 78 | 79 | const textLabelProps = input.label('name'); 80 | expect(textLabelProps.htmlFor).toEqual('form-name'); 81 | expect(customInputFormat).toHaveBeenNthCalledWith(3, 'name'); 82 | }); 83 | 84 | it('does not return IDs when formOptions.withIds is set to false', () => { 85 | const { result } = renderHook(() => useFormState()); 86 | const [, input] = result.current; 87 | const nameInputProps = input.checkbox('name', 0); 88 | const nameLabelProps = input.label('name', 0); 89 | expect(nameInputProps).not.toHaveProperty('id'); 90 | expect(nameLabelProps).not.toHaveProperty('htmlFor'); 91 | }); 92 | }); 93 | -------------------------------------------------------------------------------- /test/useFormState-manual-updates.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { renderWithFormState } from './test-utils'; 3 | 4 | describe('useFormState manual updates', () => { 5 | it('clears a field using form.clearField', () => { 6 | const { formState, change } = renderWithFormState(([, input]) => ( 7 | 8 | )); 9 | 10 | change({ value: 'waseem' }); 11 | expect(formState.current.values.name).toEqual('waseem'); 12 | 13 | formState.current.clearField('name'); 14 | expect(formState.current.values.name).toEqual(''); 15 | }); 16 | 17 | it('resets a field to its initial value on form.resetField', () => { 18 | const { formState, change } = renderWithFormState( 19 | ([, input]) => , 20 | { name: 'waseem' }, 21 | ); 22 | 23 | change({ value: 'cool' }); 24 | expect(formState.current.values.name).toEqual('cool'); 25 | 26 | formState.current.resetField('name'); 27 | expect(formState.current.values.name).toEqual('waseem'); 28 | }); 29 | 30 | it('clears the entire all form fields using form.clear', () => { 31 | const onClear = jest.fn(); 32 | const { root, formState, change, click } = renderWithFormState( 33 | ([, input]) => ( 34 |
35 | 36 | 37 | 38 | 39 |
40 | ), 41 | null, 42 | { onClear }, 43 | ); 44 | 45 | change({ value: 'bruce' }, root.childNodes[0]); 46 | change({ value: 'wayne' }, root.childNodes[1]); 47 | click({}, root.childNodes[2]); 48 | expect(formState.current.values).toEqual({ 49 | first: 'bruce', 50 | last: 'wayne', 51 | role: ['admin'], 52 | }); 53 | 54 | formState.current.clear(); 55 | expect(formState.current.values).toEqual({ 56 | first: '', 57 | last: '', 58 | role: [], 59 | }); 60 | expect(onClear).toHaveBeenCalled(); 61 | }); 62 | 63 | it('resets the entire all form fields to their initial values using form.reset', () => { 64 | const onReset = jest.fn(); 65 | const initialState = { 66 | first: 'waseem', 67 | last: 'dahman', 68 | role: ['user'], 69 | }; 70 | 71 | const { root, formState, change, click } = renderWithFormState( 72 | ([, input]) => ( 73 |
74 | 75 | 76 | 77 | 78 |
79 | ), 80 | initialState, 81 | { onReset }, 82 | ); 83 | 84 | change({ value: 'bruce' }, root.childNodes[0]); 85 | change({ value: 'wayne' }, root.childNodes[1]); 86 | click({}, root.childNodes[3]); 87 | expect(formState.current.values).toEqual({ 88 | first: 'bruce', 89 | last: 'wayne', 90 | role: [], 91 | }); 92 | 93 | formState.current.reset(); 94 | expect(formState.current.values).toEqual(initialState); 95 | expect(onReset).toHaveBeenCalled(); 96 | }); 97 | 98 | it('resets an un-mounted for field', () => { 99 | const initialState = { 100 | first: 'bruce', 101 | last: 'wayne', 102 | }; 103 | 104 | const { root, formState, change } = renderWithFormState( 105 | ([, input]) => , 106 | initialState, 107 | ); 108 | 109 | change({ value: '' }, root); 110 | expect(formState.current.values).toEqual({ 111 | first: '', 112 | last: 'wayne', 113 | }); 114 | 115 | formState.current.reset(); 116 | expect(formState.current.values).toEqual(initialState); 117 | }); 118 | 119 | it('sets the value of an input programmatically using from.setField', () => { 120 | const { formState } = renderWithFormState(([, input]) => ( 121 | 122 | )); 123 | 124 | formState.current.setField('name', 'waseem'); 125 | expect(formState.current.values.name).toBe('waseem'); 126 | }); 127 | 128 | it('sets the error of an input and invalidates the input programmatically using from.setFieldError', () => { 129 | const { formState } = renderWithFormState(([, input]) => ( 130 | 131 | )); 132 | 133 | formState.current.setFieldError('name', 'incorrect name'); 134 | expect(formState.current.validity.name).toBe(false); 135 | expect(formState.current.errors.name).toBe('incorrect name'); 136 | }); 137 | }); 138 | -------------------------------------------------------------------------------- /src/index.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for react-use-form-state 0.12.1 2 | // Project: https://github.com/wsmd/react-use-form-state 3 | // Definitions by: Waseem Dahman 4 | 5 | type StateShape = { [key in keyof T]: any }; 6 | 7 | // Even though we're accepting a number as a default value for numeric inputs 8 | // (e.g. type=number and type=range), the value stored in state for those 9 | // inputs will be a string 10 | type StateValues = { 11 | readonly [A in keyof T]: T[A] extends number ? string : T[A]; 12 | }; 13 | 14 | type StateErrors = { 15 | readonly [A in keyof T]?: E | string; 16 | }; 17 | 18 | interface UseFormStateHook { 19 | (initialState?: Partial> | null, options?: FormOptions): [ 20 | FormState, 21 | Inputs, 22 | ]; 23 | , E = StateErrors>( 24 | initialState?: Partial | null, 25 | options?: FormOptions, 26 | ): [FormState, Inputs]; 27 | } 28 | 29 | export const useFormState: UseFormStateHook; 30 | 31 | interface FormState> { 32 | values: StateValues; 33 | errors: E; 34 | validity: { readonly [A in keyof T]?: boolean }; 35 | touched: { readonly [A in keyof T]?: boolean }; 36 | pristine: { readonly [A in keyof T]: boolean }; 37 | reset(): void; 38 | clear(): void; 39 | setField(name: K, value: T[K]): void; 40 | setFieldError(name: keyof T, error: any): void; 41 | clearField(name: keyof T): void; 42 | resetField(name: keyof T): void; 43 | isPristine(): boolean; 44 | } 45 | 46 | interface FormOptions { 47 | onChange?( 48 | event: React.ChangeEvent, 49 | stateValues: StateValues, 50 | nextStateValues: StateValues, 51 | ): void; 52 | onBlur?(event: React.FocusEvent): void; 53 | onClear?(): void; 54 | onReset?(): void; 55 | onTouched?(event: React.FocusEvent): void; 56 | validateOnBlur?: boolean; 57 | withIds?: boolean | ((name: string, value?: string) => string); 58 | } 59 | 60 | // Inputs 61 | 62 | interface Inputs { 63 | selectMultiple: InputInitializer>; 64 | select: InputInitializer>; 65 | email: InputInitializer>; 66 | color: InputInitializer>; 67 | password: InputInitializer>; 68 | text: InputInitializer>; 69 | textarea: InputInitializer>; 70 | url: InputInitializer>; 71 | search: InputInitializer>; 72 | number: InputInitializer>; 73 | range: InputInitializer>; 74 | tel: InputInitializer>; 75 | date: InputInitializer>; 76 | month: InputInitializer>; 77 | week: InputInitializer>; 78 | time: InputInitializer>; 79 | radio: InputInitializerWithOwnValue>; 80 | checkbox: InputInitializerWithOptionalOwnValue>; 81 | raw: RawInputInitializer; 82 | label(name: string, value?: string): LabelProps; 83 | id(name: string, value?: string): string; 84 | } 85 | 86 | interface InputInitializer { 87 | (options: InputOptions): InputProps; 88 | (name: K): InputProps; 89 | } 90 | 91 | interface InputInitializerWithOwnValue { 92 | (options: InputOptions): R; 93 | (name: K, value: OwnValueType): R; 94 | } 95 | 96 | interface InputInitializerWithOptionalOwnValue { 97 | (options: InputOptions): R; 98 | (name: K, value?: OwnValueType): R; 99 | } 100 | 101 | interface RawInputInitializer { 102 | ( 103 | options: RawInputOptions, 104 | ): RawInputProps; 105 | (name: K): RawInputProps; 106 | } 107 | 108 | type InputOptions = { 109 | name: K; 110 | validateOnBlur?: boolean; 111 | touchOnChange?: boolean; 112 | onChange?(event: React.ChangeEvent): void; 113 | onBlur?(event: React.FocusEvent): void; 114 | compare?(initialValue: StateValues[K], value: StateValues[K]): boolean; 115 | validate?( 116 | value: string, 117 | values: StateValues, 118 | event: React.ChangeEvent | React.FocusEvent, 119 | ): any; 120 | } & OwnOptions; 121 | 122 | interface RawInputOptions { 123 | name: K; 124 | touchOnChange?: boolean; 125 | validateOnBlur?: boolean; 126 | onBlur?(...args: any[]): void; 127 | onChange?(rawValue: RawValue): StateValues[K]; 128 | compare?(initialValue: StateValues[K], value: StateValues[K]): boolean; 129 | validate?(value: StateValues[K], values: StateValues, rawValue: RawValue): any; 130 | } 131 | 132 | interface RawInputProps { 133 | name: Extract; 134 | value: StateValues[K]; 135 | onChange(rawValue: RawValue): any; 136 | onBlur(...args: any[]): any; 137 | } 138 | 139 | type InputElement = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement; 140 | 141 | type OwnValueType = string | number | boolean | string[]; 142 | 143 | interface BaseInputProps { 144 | id: string; 145 | onChange(event: any): void; 146 | onBlur(event: any): void; 147 | value: string; 148 | name: Extract; 149 | type: string; 150 | } 151 | 152 | type TypeLessInputProps = Omit, 'type'>; 153 | 154 | interface CheckableInputProps extends BaseInputProps { 155 | checked: boolean; 156 | } 157 | 158 | interface SelectMultipleProps extends TypeLessInputProps { 159 | multiple: boolean; 160 | } 161 | 162 | interface LabelProps { 163 | htmlFor: string; 164 | } 165 | 166 | type Omit = Pick>; 167 | -------------------------------------------------------------------------------- /test/useFormState-pristine.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { renderWithFormState, renderHook } from './test-utils'; 3 | import { useFormState } from '../src'; 4 | 5 | describe('useFormState pristine', () => { 6 | it('has an pristine object', () => { 7 | const { result } = renderHook(() => useFormState()); 8 | const [formState] = result.current; 9 | expect(formState).toHaveProperty('pristine', {}); 10 | }); 11 | 12 | it('marks input as not pristine', () => { 13 | const { change, formState } = renderWithFormState(([, { text }]) => ( 14 | 15 | )); 16 | change({ value: 'someval' }); 17 | expect(formState.current.pristine).toHaveProperty('name', false); 18 | }); 19 | 20 | it('marks input as not pristine when have default value', () => { 21 | const initialData = { name: 'someval' }; 22 | 23 | const { change, formState } = renderWithFormState( 24 | ([, { text }]) => , 25 | initialData, 26 | ); 27 | 28 | change({ value: 'someotherval' }); 29 | 30 | expect(formState.current.pristine).toHaveProperty('name', false); 31 | change({ value: 'someval' }); 32 | 33 | expect(formState.current.pristine).toHaveProperty('name', true); 34 | }); 35 | 36 | it('reset marks input as pristine when have default value', () => { 37 | const initialData = { name: 'someval' }; 38 | 39 | const { change, formState } = renderWithFormState( 40 | ([, { text }]) => , 41 | initialData, 42 | ); 43 | change({ value: 'someotherval' }); 44 | expect(formState.current.pristine).toHaveProperty('name', false); 45 | 46 | formState.current.resetField('name'); 47 | expect(formState.current.pristine).toHaveProperty('name', true); 48 | }); 49 | 50 | it('manually sets the pristine value of an input using setField', () => { 51 | const { formState } = renderWithFormState( 52 | ([, { text }]) => , 53 | { name: 'someval' }, 54 | ); 55 | expect(formState.current.pristine).toHaveProperty('name', true); 56 | formState.current.setField('name', 'otherval'); 57 | expect(formState.current.pristine).toHaveProperty('name', false); 58 | }); 59 | 60 | it('marks input back as pristine', () => { 61 | const { change, formState } = renderWithFormState(([, { text }]) => ( 62 | 63 | )); 64 | change({ value: 'someval' }); 65 | expect(formState.current.pristine).toHaveProperty('name', false); 66 | change({ value: '' }); 67 | expect(formState.current.pristine).toHaveProperty('name', true); 68 | }); 69 | 70 | it('handles pristine on raw values', () => { 71 | let onChange; 72 | const { formState } = renderWithFormState(([, { raw }]) => { 73 | const inputProps = raw({ name: 'name' }); 74 | ({ onChange } = inputProps); 75 | return ; 76 | }); 77 | expect(formState.current.pristine).toHaveProperty('name', true); 78 | onChange({ foo: 'someval' }); 79 | expect(formState.current.pristine).toHaveProperty('name', false); 80 | onChange(''); 81 | expect(formState.current.pristine).toHaveProperty('name', true); 82 | }); 83 | 84 | it('warns when a custom compare of "raw" is not specified', () => { 85 | const { change } = renderWithFormState( 86 | ([, { raw }]) => ( 87 | true })} /> 88 | ), 89 | { test: 'foo' }, 90 | ); 91 | change({ value: 'test' }); 92 | expect(console.warn.mock.calls[0]).toMatchInlineSnapshot(` 93 | Array [ 94 | "[useFormState]", 95 | "You used a raw input type for \\"test\\" without providing a custom compare method. As a result, the pristine value of this input will be calculated using strict equality check (====), which is insufficient. Please provide a custom compare method for this input in order to get an accurate pristine value.", 96 | ] 97 | `); 98 | }); 99 | 100 | it('handles pristine on raw default value', () => { 101 | const initialData = { name: { foo: 'someval' } }; 102 | const isEqual = (a, b) => a.foo === b.foo; 103 | let onChange; 104 | const { formState } = renderWithFormState(([, { raw }]) => { 105 | const inputProps = raw({ 106 | name: 'name', 107 | validate: () => true, 108 | compare: (initialValue, value) => isEqual(initialValue, value), 109 | }); 110 | ({ onChange } = inputProps); 111 | return ; 112 | }, initialData); 113 | 114 | onChange({ foo: 'otherval' }); 115 | expect(formState.current.pristine).toHaveProperty('name', false); 116 | onChange({ foo: 'someval' }); 117 | expect(formState.current.pristine).toHaveProperty('name', true); 118 | expect(console.warn).not.toHaveBeenCalled(); 119 | }); 120 | 121 | it('calls options.compare when an input changes', () => { 122 | const compareHandler = jest.fn(); 123 | const { change } = renderWithFormState(([, { text }]) => ( 124 | 125 | )); 126 | change({ value: 'someval' }); 127 | expect(compareHandler).toHaveBeenCalledTimes(1); 128 | }); 129 | 130 | it('handles pristine of checkbox inputs', () => { 131 | const initialState = { permission: ['1', '2', '4'] }; 132 | const { formState, click } = renderWithFormState( 133 | ([, { checkbox }]) => , 134 | initialState, 135 | ); 136 | expect(formState.current.pristine).toHaveProperty('permission', true); 137 | click(); 138 | expect(formState.current.pristine).toHaveProperty('permission', false); 139 | click(); 140 | expect(formState.current.pristine).toHaveProperty('permission', true); 141 | }); 142 | 143 | it.each([ 144 | ['undefined', undefined], 145 | ['empty string', ''], 146 | ])('initial value %s is treated as pristine', (name, testValue) => { 147 | const initialData = { name: testValue }; 148 | const { formState, change } = renderWithFormState( 149 | ([, { text }]) => , 150 | initialData, 151 | ); 152 | change({ value: 'someval' }); 153 | expect(formState.current.pristine).toHaveProperty('name', false); 154 | change({ value: '' }); 155 | expect(formState.current.pristine).toHaveProperty('name', true); 156 | }); 157 | 158 | it('reports whether the form is pristine or not', () => { 159 | const { change, formState } = renderWithFormState(([, { text }]) => ( 160 | 161 | )); 162 | expect(formState.current.isPristine()).toBe(true); 163 | change({ value: 'someval' }); 164 | expect(formState.current.isPristine()).toBe(false); 165 | }); 166 | }); 167 | -------------------------------------------------------------------------------- /test/useFormState-validation.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { renderWithFormState, renderHook } from './test-utils'; 3 | import { useFormState } from '../src'; 4 | 5 | const INPUT_CHANGE_EVENT = expect.any(Object); 6 | 7 | describe('passing a custom input validate function', () => { 8 | it('calls input validate function', () => { 9 | const validate = jest.fn(() => false); 10 | const { change, blur, formState } = renderWithFormState(([, { text }]) => ( 11 | 12 | )); 13 | 14 | expect(validate).not.toHaveBeenCalled(); 15 | change({ value: 'test' }); 16 | expect(validate).toHaveBeenCalledWith( 17 | 'test', 18 | { name: 'test' }, 19 | INPUT_CHANGE_EVENT, 20 | ); 21 | 22 | // making sure we're ignoring HTML5 validity on onBlur (input will be set as valid otherwise) 23 | blur(); 24 | expect(formState.current.validity).toHaveProperty('name', false); 25 | }); 26 | 27 | it('calls input validate function on blur with validateOnBlur', () => { 28 | const validate = jest.fn(() => false); 29 | const { change, blur } = renderWithFormState(([, { text }]) => ( 30 | 31 | )); 32 | 33 | change({ value: 'test' }); 34 | expect(validate).not.toHaveBeenCalled(); 35 | blur(); 36 | expect(validate).toHaveBeenCalledWith( 37 | 'test', 38 | { name: 'test' }, 39 | INPUT_CHANGE_EVENT, 40 | ); 41 | }); 42 | 43 | it('calls input validate function on blur with validateOnBlur on formState', () => { 44 | const validate = jest.fn(() => false); 45 | const { change, blur } = renderWithFormState( 46 | ([, { text }]) => , 47 | {}, 48 | { validateOnBlur: true }, 49 | ); 50 | 51 | change({ value: 'test' }); 52 | expect(validate).not.toHaveBeenCalled(); 53 | blur(); 54 | expect(validate).toHaveBeenCalledWith( 55 | 'test', 56 | { name: 'test' }, 57 | INPUT_CHANGE_EVENT, 58 | ); 59 | }); 60 | 61 | it('does not validate input on blur when validateOnBlur is false', () => { 62 | const validate = jest.fn(() => false); 63 | const { change, blur } = renderWithFormState(([, { text }]) => ( 64 | 65 | )); 66 | change({ value: 'test' }); 67 | expect(validate).toHaveBeenCalled(); 68 | blur(); 69 | expect(validate).toHaveBeenCalledTimes(1); 70 | }); 71 | 72 | it('marks input as valid', () => { 73 | const { change, formState } = renderWithFormState(([, { text }]) => ( 74 | 83 | )); 84 | change({ value: 'pass' }); 85 | expect(formState.current.validity).toHaveProperty('name', true); 86 | change({ value: 'other' }); 87 | expect(formState.current.validity).toHaveProperty('name', true); 88 | }); 89 | 90 | it('marks input as invalid', () => { 91 | const validate = value => value !== 'fail'; 92 | const { change, formState } = renderWithFormState(([, { text }]) => ( 93 | 94 | )); 95 | change({ value: 'fail' }); 96 | expect(formState.current.validity).toHaveProperty('name', false); 97 | expect(formState.current.errors).not.toHaveProperty('name', false); 98 | change({ value: 'pass' }); 99 | expect(formState.current.validity).toHaveProperty('name', true); 100 | }); 101 | 102 | it('has an errors object', () => { 103 | const { result } = renderHook(() => useFormState()); 104 | const [formState] = result.current; 105 | expect(formState).toHaveProperty('errors', {}); 106 | }); 107 | 108 | it('sets a custom error when validates return an error', () => { 109 | const validate = jest.fn(val => (val === 'pass' ? true : 'wrong!')); 110 | const { formState, change } = renderWithFormState(([, { text }]) => ( 111 | 112 | )); 113 | 114 | change({ value: 'fail' }); 115 | expect(formState.current.validity).toHaveProperty('name', false); 116 | expect(formState.current.errors).toHaveProperty('name', 'wrong!'); 117 | 118 | change({ value: 'pass' }); 119 | expect(formState.current.validity).toHaveProperty('name', true); 120 | expect(formState.current.errors).not.toHaveProperty('name'); 121 | }); 122 | 123 | it('handles validation of raw values', () => { 124 | const validate = jest.fn(val => (val.foo === 'pass' ? true : 'wrong!')); 125 | let onChange; 126 | const { formState } = renderWithFormState(([, { raw }]) => { 127 | const inputProps = raw({ name: 'name', validate }); 128 | ({ onChange } = inputProps); 129 | return ; 130 | }); 131 | 132 | onChange({ foo: 'fail' }); 133 | expect(formState.current.validity).toHaveProperty('name', false); 134 | expect(formState.current.errors).toHaveProperty('name', 'wrong!'); 135 | 136 | onChange({ foo: 'pass' }); 137 | expect(formState.current.validity).toHaveProperty('name', true); 138 | expect(formState.current.errors).not.toHaveProperty('name'); 139 | }); 140 | 141 | it('handles validation of raw values on blur', () => { 142 | const validate = jest.fn(val => 143 | val && val.foo === 'pass' ? true : 'wrong!', 144 | ); 145 | let onChange; 146 | let onBlur; 147 | const { formState } = renderWithFormState(([, { raw }]) => { 148 | const inputProps = raw({ name: 'name', validate }); 149 | ({ onChange, onBlur } = inputProps); 150 | return ; 151 | }); 152 | 153 | onChange({ foo: 'fail' }); 154 | onBlur(); 155 | expect(formState.current.validity).toHaveProperty('name', false); 156 | expect(formState.current.errors).toHaveProperty('name', 'wrong!'); 157 | 158 | onChange({ foo: 'pass' }); 159 | onBlur(); 160 | expect(formState.current.validity).toHaveProperty('name', true); 161 | expect(formState.current.errors).not.toHaveProperty('name'); 162 | }); 163 | 164 | it.each([ 165 | ['empty array', []], 166 | ['empty object', {}], 167 | ['empty Set', new Set()], 168 | ['empty Map', new Map()], 169 | ['empty string', ''], 170 | ['boolean (false)', false], 171 | ['null', null], 172 | ])('does not treat %s as validation error', (name, testValue) => { 173 | const { formState, change } = renderWithFormState(([, { text }]) => ( 174 | testValue })} /> 175 | )); 176 | change({ value: 'a' }); 177 | expect(formState.current.errors).not.toHaveProperty('name'); 178 | }); 179 | 180 | it.each([ 181 | ['array', ['error']], 182 | ['object', { error: 'error' }], 183 | ['Set', new Set(['error'])], 184 | ['Map', new Map([['error', 'error']])], 185 | ['string', 'error'], 186 | ['number', 0], 187 | ])('treats %s as validation error', (name, testValue) => { 188 | const { formState, change } = renderWithFormState(([, { text }]) => ( 189 | testValue })} /> 190 | )); 191 | change({ value: 'a' }); 192 | expect(formState.current.errors).toHaveProperty('name', testValue); 193 | }); 194 | }); 195 | -------------------------------------------------------------------------------- /test/types.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC } from 'react'; 2 | import { useFormState, FormState } from '../src'; 3 | 4 | useFormState(); 5 | useFormState({}); 6 | useFormState(null); 7 | 8 | interface FormFields { 9 | name: string; 10 | colors: string[]; 11 | power_level: number; 12 | remember_me: boolean; 13 | } 14 | 15 | const initialState = { 16 | name: 'wsmd', 17 | }; 18 | 19 | const [formState, input] = useFormState(initialState, { 20 | onChange(e, stateValues, nextStateValues) { 21 | const { name, value } = e.target; 22 | if (name === 'name') { 23 | // string 24 | stateValues[name].toLowerCase(); 25 | } 26 | if (name === 'colors') { 27 | // string[] 28 | stateValues[name].forEach(color => console.log(color)); 29 | } 30 | }, 31 | onBlur(e) { 32 | const { name, value } = e.target; 33 | }, 34 | onTouched(e) { 35 | const { name, value } = e.target; 36 | }, 37 | withIds: (name, value) => (value ? `${name}.${value.toLowerCase()}` : name), 38 | validateOnBlur: true, 39 | }); 40 | 41 | let name: string = formState.values.name; 42 | 43 | formState.values.colors.forEach(color => console.log(color)); 44 | 45 | /** 46 | * numeric values will be retrieved as strings 47 | */ 48 | let level: string = formState.values.power_level; 49 | 50 | let rememberMe: boolean = formState.values.remember_me; 51 | 52 | /** 53 | * values of validity and touched will be determined via the blur event. Until 54 | * the even is fired, the values will be of type undefined 55 | */ 56 | formState.touched.colors; 57 | formState.validity.name; 58 | formState.values.power_level.split(''); 59 | if (formState.errors.colors) { 60 | // string 61 | formState.errors.colors.toLocaleLowerCase(); 62 | } 63 | 64 | ; 65 | ; 66 | ; 67 | ; 68 | ; 69 | ; 70 | ; 71 | ; 72 | ; 73 | ; 74 | ; 75 | ; 76 | ; 77 | ; 78 | ; 79 | ; 80 | ; 81 | ; 82 | ; 83 | 84 | ; 86 | 87 |