formik icon indicating copy to clipboard operation
formik copied to clipboard

add submitCount to useField

Open giladv opened this issue 6 years ago • 6 comments

🚀 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>

giladv avatar Jan 14 '20 14:01 giladv

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 avatar Jan 18 '20 10:01 mrmuhammadali

@mrmuhammadali this is only true if you provide initialValues prop with all the fields. otherwise it won't work. very uncomfortable

giladv avatar Jan 19 '20 07:01 giladv

@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.

johnrom avatar Jan 20 '20 20:01 johnrom

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 ?

clementoriol avatar Nov 19 '20 16:11 clementoriol

Any news on this case?

jfortez avatar Dec 01 '22 17:12 jfortez

const formik = useFormikContext();

if (formik.submitCount > 0) {
    meta.touched = true;
}

sorotsj avatar Jul 20 '24 17:07 sorotsj