From 15efb5f5dd33e91544ed5b29733cdc494ce91f1f Mon Sep 17 00:00:00 2001 From: Tameem Bin Haider Date: Tue, 24 Dec 2024 18:28:42 +0600 Subject: [PATCH] fix: stop revalidating with stale values (#8193) --- .../src/components/form/FormFieldGenerator.tsx | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/packages/client/src/components/form/FormFieldGenerator.tsx b/packages/client/src/components/form/FormFieldGenerator.tsx index 384c9f62b43..3118753a08e 100644 --- a/packages/client/src/components/form/FormFieldGenerator.tsx +++ b/packages/client/src/components/form/FormFieldGenerator.tsx @@ -184,7 +184,7 @@ type GeneratedInputFieldProps = { disabled?: boolean onUploadingStateChanged?: (isUploading: boolean) => void requiredErrorMessage?: MessageDescriptor - setFieldTouched: (name: string, isTouched?: boolean) => void + setFieldTouched: FormikProps['setFieldTouched'] } & Omit const GeneratedInputField = React.memo( @@ -274,8 +274,18 @@ const GeneratedInputField = React.memo( extraValue={fieldDefinition.extraValue || ''} hideOnEmptyOption={fieldDefinition.hideOnEmptyOption} onComplete={(files: IFileValue[]) => { + /* + * calling both setFieldTouched and setFieldValue causes the validate + * function to be called twice, once with the stale values (due to + * setFieldTouched) and the other with the updated values (due to + * setFieldValue). So if setFieldTouched is called after + * setFieldValue then wrong validations are shown due to the stale + * values. We can prevent that by supplying shouldRevalidate = + * false to the setFieldTouch function or calling it before + * calling setFieldValue. + */ + setFieldTouched(fieldDefinition.name, true, false) setFieldValue(fieldDefinition.name, files) - setFieldTouched && setFieldTouched(fieldDefinition.name, true) }} compressImagesToSizeMB={fieldDefinition.compressImagesToSizeMB} maxSizeMB={fieldDefinition.maxSizeMB} @@ -296,7 +306,7 @@ const GeneratedInputField = React.memo( files={value as IAttachmentValue} error={error} onComplete={(file) => { - setFieldTouched && setFieldTouched(fieldDefinition.name, true) + setFieldTouched(fieldDefinition.name, true, false) setFieldValue(fieldDefinition.name, file) }} onUploadingStateChanged={onUploadingStateChanged}