fix(striker-ui): prevent submit during input change in formik utils

main
Tsu-ba-me 9 months ago
parent dcde1f9051
commit 231a1a0537
  1. 33
      striker-ui/hooks/useFormikUtils.ts

@ -1,6 +1,6 @@
import { FormikConfig, FormikValues, useFormik } from 'formik'; import { FormikConfig, FormikValues, useFormik } from 'formik';
import { isEqual, isObject } from 'lodash'; import { isEqual, isObject } from 'lodash';
import { useCallback, useMemo } from 'react'; import { useCallback, useMemo, useState } from 'react';
import debounce from '../lib/debounce'; import debounce from '../lib/debounce';
import getFormikErrorMessages from '../lib/getFormikErrorMessages'; import getFormikErrorMessages from '../lib/getFormikErrorMessages';
@ -29,6 +29,8 @@ const isChainEqual = (
const useFormikUtils = <Values extends FormikValues = FormikValues>( const useFormikUtils = <Values extends FormikValues = FormikValues>(
formikConfig: FormikConfig<Values>, formikConfig: FormikConfig<Values>,
): FormikUtils<Values> => { ): FormikUtils<Values> => {
const [changing, setChanging] = useState<boolean>(false);
const formik = useFormik<Values>({ ...formikConfig }); const formik = useFormik<Values>({ ...formikConfig });
const getFieldChanged = useCallback( const getFieldChanged = useCallback(
@ -40,18 +42,37 @@ const useFormikUtils = <Values extends FormikValues = FormikValues>(
[formik.initialValues, formik.values], [formik.initialValues, formik.values],
); );
const debounceHandleChange = useMemo( const debounceHandleChange = useMemo(() => {
() => debounce(formik.handleChange), const base = debounce((...args: Parameters<typeof formik.handleChange>) => {
[formik.handleChange], formik.handleChange(...args);
); setChanging(false);
});
return (...args: Parameters<typeof base>) => {
setChanging(true);
base(...args);
};
// Only handle change is being used in the debounced function, no need to
// add the whole formik object as dependency.
//
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [formik.handleChange]);
const disabledSubmit = useMemo( const disabledSubmit = useMemo(
() => () =>
changing ||
!formik.dirty || !formik.dirty ||
!formik.isValid || !formik.isValid ||
formik.isValidating || formik.isValidating ||
formik.isSubmitting, formik.isSubmitting,
[formik.dirty, formik.isSubmitting, formik.isValid, formik.isValidating], [
changing,
formik.dirty,
formik.isSubmitting,
formik.isValid,
formik.isValidating,
],
); );
const formikErrors = useMemo<Messages>( const formikErrors = useMemo<Messages>(

Loading…
Cancel
Save