add submitCount to useField
🚀 Feature request
Current Behavior
currently there's no way to build a field which shows the error after the field was touched or the form was submitted with the useField hook.
Desired Behavior
const [field, meta, helpers, form] = useField(props);
and:
(meta.touched || form.submitCount) && meta.error && <div>{meta.error}</div>
All of the registered fields get tocuhed when a form is submitted so there is no need to check for form.submitCount. You can fulfill your use case by dispatching onBlur event of the field or explicitly calling helpers.setTouched(true).
@mrmuhammadali this is only true if you provide initialValues prop with all the fields. otherwise it won't work. very uncomfortable
@giladv this is true, and unfortunately is how Formik works. Formik's API isn't currently built around <Field /> registration, because Fields may or may not be rendered at a given time. InitialValues is described as required at the following locations:
https://github.com/jaredpalmer/formik/issues/445#issuecomment-366952762 https://jaredpalmer.com/formik/docs/guides/form-submission#pre-submit
@jaredpalmer we might want to make this fact more prevalent in the overview and/or tutorial pages. The first paragraph where Formik props are described should clearly state that initialValues is the model which Formik's internal state is based upon. It's very clear in TypeScript but not everyone uses it.
Bumping this, I've got clients often asking for the "show errors only after 1 submit", and while this is doable by using useFormikContext from the field to get the submitCount, I'd prefer to avoid getting the whole context each time, especially now that v3 optimizations are coming.
Any preferred way of doing this ?
Any news on this case?
const formik = useFormikContext();
if (formik.submitCount > 0) {
meta.touched = true;
}