Last active
August 14, 2024 07:56
-
-
Save AlonMiz/e583946d3978de691ed53cece972e1a1 to your computer and use it in GitHub Desktop.
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 { useCallback, useEffect, useRef } from 'react'; | |
import { debounce } from 'lodash'; | |
import { FormikValues } from 'formik'; | |
import { FormikConfig } from 'formik/dist/types'; | |
export function useDebouncedValidate<T extends FormikValues>({ | |
values, | |
validate, | |
debounceTime = 200, | |
}: { | |
values: T; | |
validate: FormikConfig<T>['validate']; | |
debounceTime?: number; | |
}) { | |
const debouncedFunction = useRef( | |
debounce((validateFunc: FormikConfig<T>['validate'], data: T) => { | |
return validateFunc(data); | |
}, debounceTime), | |
); | |
const debounceValidate = useCallback(data => { | |
return debouncedFunction.current(validate, data); | |
}, []); | |
useEffect(() => { | |
debounceValidate(values); | |
}, [values]); | |
useEffect(() => { | |
return () => { | |
debouncedFunction.current.cancel(); | |
}; | |
}, []); | |
} | |
// usage | |
import React from 'react'; | |
import { FormikProvider, useFormik, Field } from 'formik'; | |
import * as Yup from 'yup'; | |
const initialValues = { name: '' }; | |
const formSchema = Yup.object().shape({ | |
name: Yup.string().required('Required'), | |
}); | |
const SimpleForm = () => { | |
const formMethods = useFormik({ | |
initialValues, | |
validationSchema: formSchema, | |
validateOnChange: false, | |
onSubmit: async () => { | |
console.log('Form submitted'); | |
}, | |
}); | |
useDebouncedValidate({ | |
validate: values => { | |
console.log('validating',values); | |
formMethods.validateForm(values); | |
}, | |
debounceTime: 200, | |
values: formMethods.values, | |
}); | |
return ( | |
<FormikProvider value={formMethods}> | |
<Field label={'name'} name={'name'} /> | |
</FormikProvider> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks bro