SHARE
TWEET

Untitled

a guest Oct 19th, 2019 82 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useState, useEffect } from 'react';
  2. import { useFormikContext, FieldMetaProps } from 'formik';
  3.  
  4. export function useTouchedHandler(name: string, meta: FieldMetaProps<any>) {
  5.   const { setFieldTouched } = useFormikContext<any>();
  6.  
  7.   // use meta.touched as the initial value to keep the state,
  8.   // in case this field was unmounted
  9.   const [wasChanged, setWasChanged] = useState(meta.touched);
  10.  
  11.   // track if it was changed a least *once*
  12.   useEffect(() => {
  13.     if (meta.value !== meta.initialValue) {
  14.       setWasChanged(true);
  15.     }
  16.   }, [meta.value, meta.initialValue]);
  17.  
  18.   useEffect(() => {
  19.     // formik marks fields as *not* touched, if it was
  20.     // *restored* to the initial value - but we *do* want that
  21.     if (!meta.touched && wasChanged) {
  22.       setFieldTouched(name, true, false);
  23.       // on the other hand there can be cases (on blur) where the field
  24.       // is marked as touched even though the user never entered something
  25.       // - but we *don't* want that
  26.     } else if (meta.touched && !wasChanged) {
  27.       setFieldTouched(name, false, false);
  28.     }
  29.   }, [meta.touched, name, setFieldTouched, wasChanged]);
  30. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top