I'm submitting a form using Formik. I want to have slightly different validation logic depending on whether it's being triggered by blur/change events or pre-submit validation. (Long story short, during pre-submit, I only want to run sync validation — my back end will do the same async validation that I run on blur/change when I submit the form, so I want to skip it in pre-submit.) My validate function looks something like this:
validate={(value) => {
const error = validateSync(value);
if (!error && !form.isSubmitting) {
return validateAsync(value);
}
return error;
}}
In this case, I'm using useFormikContext to get form.isSubmitting.
According to the Formik docs on submission, isSubmitting should be set to true immediately in the Pre-submit stage, before the Validation stage. This doesn't seem to be happening, as you can see if you try to submit the form in this sandbox (check the console to see that both isSubmitting and isValidating are false — according to the Formik docs, they should both be true at this stage).
Another user had a similar question, but the answer doesn't address the underlying (possible) bug with Formik.
Used React's useRef hook to reference the current version of the form:
const form = useFormikContext();
const formRef = useRef();
formRef.current = form;
// within a delayed callback:
function delayedCallback() {
// pulls the current value of isSubmitting, whenever the delayedCallback fires
const { isSubmitting } = formRef.current;
};
Works 100%