Skip to content

Instantly share code, notes, and snippets.

@AlonMiz
Last active August 14, 2024 07:56
Show Gist options
  • Save AlonMiz/e583946d3978de691ed53cece972e1a1 to your computer and use it in GitHub Desktop.
Save AlonMiz/e583946d3978de691ed53cece972e1a1 to your computer and use it in GitHub Desktop.
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>
);
};
@AlonMiz
Copy link
Author

AlonMiz commented Jun 2, 2023

try simply using <Field name={'name'} />
working for me

@pedrocmota
Copy link

thanks bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment