1+ import { useRef } from 'react' ;
12import { toString , noop , omit , isFunction , isEmpty } from './utils' ;
23import { parseInputArgs } from './parseInputArgs' ;
34import { useInputId } from './useInputId' ;
45import { useCache } from './useCache' ;
56import { useState } from './useState' ;
67import {
7- TYPES ,
8+ INPUT_TYPES ,
89 SELECT ,
910 CHECKBOX ,
1011 RADIO ,
@@ -29,7 +30,7 @@ const defaultFormOptions = {
2930export default function useFormState ( initialState , options ) {
3031 const formOptions = { ...defaultFormOptions , ...options } ;
3132
32- const formState = useState ( { initialState, ... formOptions } ) ;
33+ const formState = useState ( { initialState } ) ;
3334 const { getIdProp } = useInputId ( formOptions . withIds ) ;
3435 const { set : setDirty , has : isDirty } = useCache ( ) ;
3536 const callbacks = useCache ( ) ;
@@ -290,19 +291,39 @@ export default function useFormState(initialState, options) {
290291 : inputProps ;
291292 } ;
292293
293- const inputPropsCreators = TYPES . reduce (
294- ( methods , type ) => ( { ...methods , [ type ] : createPropsGetter ( type ) } ) ,
295- { } ,
296- ) ;
297-
298- return [
299- {
300- ...formState . current ,
301- ...formState . controls ,
294+ const formStateAPI = useRef ( {
295+ clearField : formState . clearField ,
296+ resetField : formState . resetField ,
297+ setField ( name , value ) {
298+ formState . setField ( name , value , true , true ) ;
299+ } ,
300+ setFieldError ( name , error ) {
301+ formState . setValidity ( { [ name ] : false } ) ;
302+ formState . setError ( { [ name ] : error } ) ;
303+ } ,
304+ clear ( ) {
305+ formState . forEach ( formState . clearField ) ;
306+ formOptions . onClear ( ) ;
302307 } ,
303- {
304- ... inputPropsCreators ,
305- [ LABEL ] : ( name , ownValue ) => getIdProp ( 'htmlFor' , name , ownValue ) ,
308+ reset ( ) {
309+ formState . forEach ( formState . resetField ) ;
310+ formOptions . onReset ( ) ;
306311 } ,
307- ] ;
312+ } ) ;
313+
314+ // exposing current form state (e.g. values, touched, validity, etc)
315+ // eslint-disable-next-line guard-for-in, no-restricted-syntax
316+ for ( const key in formState . current ) {
317+ formStateAPI . current [ key ] = formState . current [ key ] ;
318+ }
319+
320+ const inputPropsCreators = {
321+ [ LABEL ] : ( name , ownValue ) => getIdProp ( 'htmlFor' , name , ownValue ) ,
322+ } ;
323+
324+ INPUT_TYPES . forEach ( type => {
325+ inputPropsCreators [ type ] = createPropsGetter ( type ) ;
326+ } ) ;
327+
328+ return [ formStateAPI . current , inputPropsCreators ] ;
308329}
0 commit comments