Created
November 29, 2017 18:06
-
-
Save jaredpalmer/a8faaab12bc37e6a160a3c9549664f0b to your computer and use it in GitHub Desktop.
Formik async email signup input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import debounce from 'utils/debounce'; | |
class EmailInput extends React.Component { | |
checkEmail = value => { | |
// only check if the field passes Yup email validation first | |
if ( | |
!this.props.form.errors[this.props.name].includes( | |
'invalid' /* or whatever your error message is*/ | |
) | |
) { | |
MyApi.checkEmail(value).then( | |
success => { | |
this.props.form.setFieldError(this.props.name, undefined); | |
// if you need to show more info, like a checkbox: | |
// this.props.form.setStatus({ email: true }) | |
}, | |
error => | |
this.props.form.setFieldError( | |
this.props.name, | |
transformErrorToEnglish(error) | |
) | |
); | |
} | |
}; | |
debouncedCheckEmail = debounce(this.checkEmail, 300); // 300ms debounce | |
handleChange = e => { | |
this.props.field.handleChange(e); // this will let Formik's default validation take place | |
this.debouncedCheckEmail(e.target.value); | |
}; | |
handleBlur = e => { | |
this.props.field.handleBlur(e); // this will let Formik's default validation take place | |
this.checkEmail(e.target.value); | |
}; | |
render() { | |
const { field, form, ...props /* like placeholder */ } = this.props; | |
return ( | |
<div> | |
<input | |
{...field} | |
{...props} | |
onChange={this.handleChange} | |
onBlur={this.handleBlur} | |
/> | |
{/** show errors */} | |
</div> | |
); | |
} | |
} | |
export default EmailInput | |
// Usage | |
<Field name="email" component={EmailInput} placeholder="jane@apple.com" /> | |
// or | |
<Field name="email" render={props => <EmailInput {...props} {...otherPropsYouMightNeed} />} /> |
@davetorbeck I had a similar issue with it being cleared out by my yup
validation. Might not be the best solution but if you whack a setTimeout
around it, it should run on the next loop and after the other validation has run, eg:
setTimeout(() => {
form.setFieldError(this.props.name, EMAIL_EXISTS_ERROR_MESSAGE);
}, 0)
Hello!,
I think this lines is not correct:
this.props.field.handleChange (e);
this.props.field.handleBlur (e);It should be like that, right?
this.props.form.handleChange (e);
this.props.form.handleBlur (e);
This example is so broken :( Did anyone ever get this to work and could you provide an example, please?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can confirm this also does not work for me. Any error I set with
setFieldError
is cleared out on validation of another field.