Created
October 1, 2019 13:43
-
-
Save donaldpipowitch/502cc73a7223eb56aae8009d64e34403 to your computer and use it in GitHub Desktop.
Change touch behavior of Formik
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 { 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