Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Created October 1, 2019 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donaldpipowitch/502cc73a7223eb56aae8009d64e34403 to your computer and use it in GitHub Desktop.
Save donaldpipowitch/502cc73a7223eb56aae8009d64e34403 to your computer and use it in GitHub Desktop.
Change touch behavior of Formik
import { useState, useEffect } from 'react';
import { useFormikContext, FieldMetaProps } from 'formik';
export function useTouchedHandler(name: string, meta: FieldMetaProps<any>) {
const { setFieldTouched } = useFormikContext<any>();
// use meta.touched as the initial value to keep the state,
// in case this field was unmounted
const [wasChanged, setWasChanged] = useState(meta.touched);
// track if it was changed a least *once*
useEffect(() => {
if (meta.value !== meta.initialValue) {
setWasChanged(true);
}
}, [meta.value, meta.initialValue]);
useEffect(() => {
// formik marks fields as *not* touched, if it was
// *restored* to the initial value - but we *do* want that
if (!meta.touched && wasChanged) {
setFieldTouched(name, true, false);
// on the other hand there can be cases (on blur) where the field
// is marked as touched even though the user never entered something
// - but we *don't* want that
} else if (meta.touched && !wasChanged) {
setFieldTouched(name, false, false);
}
}, [meta.touched, name, setFieldTouched, wasChanged]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment