Last active
May 10, 2023 04:07
-
-
Save sibelius/ccea4d505eb20d0dd08c19716c469093 to your computer and use it in GitHub Desktop.
useFastField that uses local state `onChange` and sync back to formik only `onBlur`
This file contains hidden or 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 React, { useState, useEffect } from 'react'; | |
import { useField, FieldHookConfig, FieldInputProps, FieldMetaProps, FieldHelperProps } from 'formik'; | |
import { useDebouncedCallback } from 'use-debounce'; | |
const DEBOUNCE_DELAY = 300; | |
export function useFastField<Val = any>( | |
propsOrFieldName: string | FieldHookConfig<Val>, | |
): [FieldInputProps<Val>, FieldMetaProps<Val>, FieldHelperProps<Val>] { | |
const [field, meta, helpers] = useField<Val>(propsOrFieldName); | |
const [value, setValue] = useState<Val>(field.value); | |
const { onBlur, onChange } = field; | |
const { setValue: helpersSetValue } = helpers; | |
const { shouldResync = true } = propsOrFieldName; | |
const currentFieldValue = field.value; | |
// resync field.value | |
useEffect(() => { | |
if (shouldResync) { | |
if (currentFieldValue !== value) { | |
setValue(currentFieldValue); | |
} | |
} | |
}, [currentFieldValue, shouldResync]); | |
const [onSync] = useDebouncedCallback((e) => { | |
onChange(e); | |
onBlur(e); | |
}, DEBOUNCE_DELAY); | |
const [onSyncValue] = useDebouncedCallback((val: Val) => { | |
helpersSetValue(val); | |
helpers.setTouched(true); | |
}, DEBOUNCE_DELAY); | |
// monkey patch formik field | |
field.value = value; | |
field.onChange = (e: React.ChangeEvent<any>): void => { | |
if (e && e.currentTarget) { | |
setValue(e.currentTarget.value); | |
} | |
onSync(e); | |
}; | |
field.onBlur = (e: any): void => { | |
onChange(e); | |
onBlur(e); | |
}; | |
helpers.setValue = (val: Val) => { | |
setValue(val); | |
onSyncValue(val); | |
}; | |
return [field, meta, helpers]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if you will set field by other field (with setFieldValue from useFormikContext)
you can use like below