Form Actions

Form actions and methods


// object
const {
  form,
  touches, isTouched,
  errors, isValid,
  context,
  field, getValue,
  triggerChange, reset, onChange, changeValue, 
  handleSubmit,
  getErrors, hasError, setError,
  watch,
  resetTouch,
  updateController
} = useForm( ... )
NameTypeDescription
formobject | classformData
touches{ [form path]: boolean }Form touches
isTouchedbooleanForm touches state by default is false if touches are undefined or an empty object
errors{ [form path]: [path error messages] }Depends if useForm validate is set.
isValidbooleanForm state by default is false if errors are undefined or an empty object
contextobjectContext, mainly for use in FormProvider

field

Method to connect the form element to the key by providing native attributes like onChange, name, etc

const {
  field
} = useForm(
  {
    name: 'Rimuru'
  }
)

<input {...field('name')} />

<input 
  { ...field('name', { 
      blur: false,
      readOnly: false,
      filterKeysError: () => false,
      forceValidation: false,
      onChange: () => {},
      triggerTouched: true,
      validate: true
    })
  } 
/>

Field options

Note: Field options are not mandatory or necessary, they are optional

NameTypeDefaultDescription
blurbooleanfalseTurns the field from a onChange to onBlur
filterKeysError(key: string) => booleanundefinedMethod to make sure some keys are not triggering errors
forceValidationbooleanfalseForces form validation regardless of conditions
onChange(value: Value) => anyundefinedChanges the value on change.
readOnlybooleanfalseTurns the field from a onChange to readonly
triggerTouchedbooleantrueIf false will not check touches and not call onTouch from options
validatebooleantrueValidates form if new form values are different from previous form values

getValue

Return the value for the matched key

const {
  getValue
} = useForm(
  {
    name: 'Rimuru'
  }
)

getValue('name') /// Rimuru

triggerChange

Method to make multiple changes in one render

const {
  triggerChange
} = useForm(
  ...
)

triggerChange((form) => {
  form.name = 'Rimuru';
  form.age = '39';
  ...
})

triggerChange((form) => {}, { 
  filterKeysError: (key) => false,
  forceValidation: false,
  triggerTouched: true,
  validate: true
})

Field options

Note: Field options are not mandatory or necessary, they are optional

NameTypeDefaultDescription
filterKeysError(key: string) => booleanundefinedMethod to make sure some keys are not triggering errors
forceValidationbooleanfalseForces form validation regardless of conditions
triggerTouchedbooleantrueIf false will not check touches and not call onTouch from options
validatebooleantrueValidates form if new form values are different from previous form values

reset

Resets form state

const {
  reset
} = useForm(
  {
    name: 'Rimuru'
  }
)
...
reset({
  name: 'Rimuru Tempest'
})

reset({ ... }, {
  filterKeysError: (key) => false,
  forceValidation: false,
  triggerTouched: true,
  validate: true,
  clearTouched: true
})

Field options

Note: Field options are not mandatory or necessary, they are optional

NameTypeDefaultDescription
filterKeysError(key: string) => booleanundefinedMethod to make sure some keys are not triggering errors
forceValidationbooleanfalseForces form validation regardless of conditions
triggerTouchedbooleantrueIf false will not check touches and not call onTouch from options
validatebooleantrueValidates form if new form values are different from previous form values
clearTouchedbooleantrueOn reset, touches will be cleared

onChange

Returns a method to change key value

const {
  onChange
} = useForm(
  {
    name: 'Rimuru'
  }
)
...
onChange('name')

<input onChange={onChange('name')} />

onChange('name', { 
  blur: false,
  readOnly: false,
  filterKeysError: () => false,
  forceValidation: false,
  onChange: () => {},
  triggerTouched: true,
  validate: true
})

Field options

Note: Field options are not mandatory or necessary, they are optional

NameTypeDefaultDescription
blurbooleanfalseTurns the field from a onChange to onBlur
filterKeysError(key: string) => booleanundefinedMethod to make sure some keys are not triggering errors
forceValidationbooleanfalseForces form validation regardless of conditions
onChange(value: Value) => anyundefinedChanges the value on change.
readOnlybooleanfalseTurns the field from a onChange to readonly
triggerTouchedbooleantrueIf false will not check touches and not call onTouch from options
validatebooleantrueValidates form if new form values are different from previous form values

changeValue

Simplified version of onChange, without the return method

const {
  changeValue
} = useForm(
  {
    name: 'Rimuru',
    age: '40'
  }
)
...
changeValue('name', 'Rimuru Tempest')

changeValue('name', 'Rimuru Tempest', { 
  blur: false,
  readOnly: false,
  filterKeysError: () => false,
  forceValidation: false,
  onChange: () => {},
  triggerTouched: true,
  validate: true
})

Field options

Note: Field options are not mandatory or necessary, they are optional

NameTypeDefaultDescription
blurbooleanfalseTurns the field from a onChange to onBlur
filterKeysError(key: string) => booleanundefinedMethod to make sure some keys are not triggering errors
forceValidationbooleanfalseForces form validation regardless of conditions
onChange(value: Value) => anyundefinedChanges the value on change.
readOnlybooleanfalseTurns the field from a onChange to readonly
triggerTouchedbooleantrueIf false will not check touches and not call onTouch from options
validatebooleantrueValidates form if new form values are different from previous form values

handleSubmit

Method to handle form submission

const onSubmit = handleSubmit((form) => {
  /// Will only be called when form is valid
  /// do something with it
})

const onSubmit = handleSubmit(
  (form) => {
    /// Will always be called 
    /// because the next method returns true
    /// do something with it
  },
  (errors) => true 
)

getErrors

Returns error messages for the matched key

const {
  getErrors
} = useForm(
  {
    product: {
      name: 'Apple',
      category: {
        name: 'Food',
        type: {
          name: 'Solid',
          type: 'Vegetal'
        }
      }
    }
  },
  {
	validate: () => {
		// Returned errors are going to be show in getErrors
		return []
	}
  }
)

getErrors('product.category') /// [<<Error Messages>>]
getErrors('product.category.type.name') /// [<<Error Messages>>]

getErrors('product.category.type.name', {
  includeChildsIntoArray: true,
  includeKeyInChildErrors: false,
  onlyOnTouch: true,
  onlyOnTouchKeys: undefined,
  strict: true
})

Field options

Note: Field options are not mandatory or necessary, they are optional

NameTypeDefaultDescription
includeChildsIntoArraybooleantrueIncludes the children errors on the array
includeKeyInChildErrorsbooleanfalseIncludes key in children paths
onlyOnTouchbooleantrueWhen true only returns if the key was touched
onlyOnTouchKeys Array<FormKey<T>>undefinedArray containing other keys to also validate on touch
strictbooleantrueIncludes children errors as objects into array. Note: If includeChildsIntoArray is true strict will by default be false

hasError

Returns a boolean for the matched key

const {
  hasError
} = useForm(
  {
    product: {
      name: 'Apple',
      category: {
        name: 'Food',
        type: {
          name: 'Solid',
          type: 'Vegetal'
        }
      }
    }
  },
  {
	validate: () => {
		// Returned errors are defined if hasError is true or false
		return []
	}
  }
)

hasError('product.category') // returns true or false
hasError('product.category.type.name') // returns true or false

Field options

Note: Field options are not mandatory or necessary, they are optional

NameTypeDefaultDescription
onlyOnTouchbooleantrueWhen true only returns if the key was touched
onlyOnTouchKeys Array<FormKey<T>>undefinedArray containing other keys to also validate on touch
strictbooleantrueIncludes children errors to define if is true or false. Note: If includeChildsIntoArray is true strict will by default be false

setError

Method to set custom errors

const {
  setError
} = useForm(
  {
    name: 'Rimuru'
  }
)

setError([
  {
    key: 'name',
    message: 'Beautiful name'
  }
])

watch

  • After all changes are done, it will execute all “watched keys” methods.
  • Watch key, then executes the method to update itself or others values.
  • Watch ‘submit’ to execute when the form is submitted.
const {
  watch
} = useForm(
  {
    name: 'Rimuru'
  }
)

// When 'name' is `touched` it will update again with the new name
// It does not rerender again, its a one time deal for every watch
// Order is important as well, as it will be executed by order in render
watch('name', (form) => {
  form.name = 'Rimuru Tempest';
})
// When form is submitted
watch('submit', (form) => {
})

resetTouch

Clears touch’s

const {
  resetTouch
} = useForm(
  ...
)
...
resetTouch()

updateController

Forces update controllers with key

const {
  updateController
} = useForm(
  ...
)

updateController("<<Some used in Controller>>")