Redux-form: Add a way to debounce `.touched`

Created on 11 May 2016  路  3Comments  路  Source: redux-form/redux-form

I would like to have a way to debounce .touched so that 500 milliseconds after the user finishes typing their current input all the validation fires.

This will allow me to do username checks while the user keeps their cursor in the username field.

question

Most helpful comment

Presumably you would need to call asyncValidate() somewhere, but if all you want is for a field to be marked touched 500ms after the first change, this should do it (handwritten untested code):

class MyForm extends Component {
  debounceTouch(field) {
    const { touch } = this.props
    if (this.debounceTimeout) {
      clearTimeout(this.debounceTimeout)
    }
    this.debounceTimeout = setTimeout(() => touch(field), 500)
  }

  render() {
    const { fields: { username }, touch, handleSubmit } = this.props
    return (
      <form onSubmit={handleSubmit}>
        <input type="text" {...username} onChange={event => {
            username.onChange(event)
            this.debounceTouch('username')
          }}/>
      </form>
    )
  }
}
export default reduxForm({
  form: 'myForm'
})(MyForm)

All 3 comments

Presumably you would need to call asyncValidate() somewhere, but if all you want is for a field to be marked touched 500ms after the first change, this should do it (handwritten untested code):

class MyForm extends Component {
  debounceTouch(field) {
    const { touch } = this.props
    if (this.debounceTimeout) {
      clearTimeout(this.debounceTimeout)
    }
    this.debounceTimeout = setTimeout(() => touch(field), 500)
  }

  render() {
    const { fields: { username }, touch, handleSubmit } = this.props
    return (
      <form onSubmit={handleSubmit}>
        <input type="text" {...username} onChange={event => {
            username.onChange(event)
            this.debounceTouch('username')
          }}/>
      </form>
    )
  }
}
export default reduxForm({
  form: 'myForm'
})(MyForm)

Can I call asyncValidate when the setTimeout fires? Or is there a better place to do so?

That solution looks like it could definitely work!

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings