Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed : Disable Submit Button #9526

Closed
wants to merge 12 commits into from
38 changes: 32 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"@googlemaps/typescript-guards": "^2.0.3",
"@headlessui/react": "^2.2.0",
"@hello-pangea/dnd": "^17.0.0",
"@hookform/resolvers": "^3.9.1",
"@pnotify/core": "^5.2.0",
"@pnotify/mobile": "^5.2.0",
"@radix-ui/react-dialog": "^1.1.4",
Expand Down Expand Up @@ -95,7 +96,9 @@
"react-copy-to-clipboard": "^5.1.0",
"react-dom": "18.3.1",
"react-google-recaptcha": "^3.1.0",

"react-i18next": "^15.2.0",

"react-infinite-scroll-component": "^6.1.0",
"react-pdf": "^9.2.1",
"react-webcam": "^7.2.0",
Expand Down Expand Up @@ -152,7 +155,7 @@
"vite-plugin-checker": "^0.8.0",
"vite-plugin-pwa": "^0.20.5",
"vite-plugin-static-copy": "^2.0.0",
"zod": "^3.23.8"
"zod": "^3.24.1"
},
"browserslist": {
"production": [
Expand Down
108 changes: 72 additions & 36 deletions src/components/Form/Form.tsx
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lets not modify the old custom Form component with new Form component from shadcn ui.

Shadcn's form is built to be used with shadcn's form fields, not our form field components.

Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { useEffect, useMemo, useRef, useState } from "react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";

import { Button } from "@/components/ui/button";

import { Cancel, Submit } from "@/components/Common/ButtonV2";
import { FieldValidator } from "@/components/Form/FieldValidators";
import {
FormContextValue,
Expand Down Expand Up @@ -43,45 +46,61 @@ const Form = <T extends FormDetails>({
hideCancelButton = false,
...props
}: Props<T>) => {
const { t } = useTranslation();
const initial = { form: props.defaults, errors: {} };
const [isLoading, setIsLoading] = useState(!!asyncGetDefaults);
const [state, dispatch] = useAutoSaveReducer<T>(formReducer, initial);
const formVals = useRef(props.defaults);

interface FormData extends FormDetails {
[key: string]: unknown;
}

const methods = useForm<FormData>({
defaultValues: props.defaults,
mode: "onChange",
});

const { formState } = methods;

useEffect(() => {
if (!asyncGetDefaults) return;

asyncGetDefaults().then((form) => {
dispatch({ type: "set_form", form });
methods.reset(form);
setIsLoading(false);
});
}, [asyncGetDefaults]);
}, [asyncGetDefaults, methods, dispatch]);

Comment on lines 66 to +74
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for async defaults.

While the synchronization of form state is good, the async operation lacks error handling.

 if (!asyncGetDefaults) return;

-asyncGetDefaults().then((form) => {
-  dispatch({ type: "set_form", form });
-  methods.reset(form);
-  setIsLoading(false);
-});
+try {
+  const form = await asyncGetDefaults();
+  dispatch({ type: "set_form", form });
+  methods.reset(form);
+} catch (error) {
+  console.error("Failed to load form defaults:", error);
+  Notification.Error({ msg: t("errors.form.loading") });
+} finally {
+  setIsLoading(false);
+}

Committable suggestion skipped: line range outside the PR's diff.

const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
event.stopPropagation();
const handleSubmit = async (data: T) => {
try {
if (validate) {
const errors = omitBy(validate(data), isEmpty) as FormErrors<T>;

if (validate) {
const errors = omitBy(validate(state.form), isEmpty) as FormErrors<T>;
if (Object.keys(errors).length) {
dispatch({ type: "set_errors", errors });

if (Object.keys(errors).length) {
dispatch({ type: "set_errors", errors });

if (errors.$all) {
Notification.Error({ msg: errors.$all });
if (errors.$all) {
Notification.Error({ msg: errors.$all });
}
return;
}
return;
}
}

const errors = await props.onSubmit(state.form);
if (errors) {
dispatch({
type: "set_errors",
errors: { ...state.errors, ...errors },
});
} else if (props.resetFormValsOnSubmit) {
dispatch({ type: "set_form", form: formVals.current });
const errors = await props.onSubmit(data);
if (errors) {
dispatch({
type: "set_errors",
errors: { ...state.errors, ...errors },
});
} else if (props.resetFormValsOnSubmit) {
dispatch({ type: "set_form", form: formVals.current });
methods.reset(formVals.current);
}
} catch (error) {
console.error("Form submission error:", error);
Notification.Error({ msg: t("errors.form.submission") });
}
};

Expand All @@ -97,10 +116,11 @@ const Form = <T extends FormDetails>({

return (
<form
onSubmit={handleSubmit}
onKeyDown={(e) => {
if (e.key === "Enter") {
handleSubmit(e);
onSubmit={methods.handleSubmit((data) => handleSubmit(data as T))}
onKeyDown={(e: React.KeyboardEvent<HTMLFormElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
methods.handleSubmit((data) => handleSubmit(data as T))();
}
}}
className={classNames(
Expand All @@ -113,6 +133,12 @@ const Form = <T extends FormDetails>({
<DraftSection
handleDraftSelect={(newState: FormState<T>) => {
dispatch({ type: "set_state", state: newState });
Object.entries(newState.form).forEach(([key, value]) => {
methods.setValue(key, value, {
shouldDirty: true,
shouldTouch: true,
});
});
props.onDraftRestore?.(newState);
}}
formData={state.form}
Expand All @@ -123,13 +149,18 @@ const Form = <T extends FormDetails>({
return {
name,
id: name,
onChange: ({ name, value }: FieldChangeEvent<T[keyof T]>) =>
onChange: ({ name, value }: FieldChangeEvent<T[keyof T]>) => {
dispatch({
type: "set_field",
name,
value,
error: validate?.(value),
}),
});
methods.setValue(name as string, value, {
shouldDirty: true,
shouldTouch: true,
});
},
value: state.form[name],
error: state.errors[name],
disabled,
Expand All @@ -141,17 +172,22 @@ const Form = <T extends FormDetails>({
</div>
<div className="flex flex-col-reverse justify-end gap-3 sm:flex-row">
{!hideCancelButton && (
<Cancel
<Button
onClick={handleCancel}
label={props.cancelLabel ?? "Cancel"}
/>
variant="secondary"
disabled={disabled}
>
{props.cancelLabel ?? t("Cancel")}
</Button>
)}
<Submit
<Button
data-testid="submit-button"
type="submit"
disabled={disabled}
label={props.submitLabel ?? "Submit"}
/>
disabled={disabled || !formState.isDirty}
variant="primary"
>
{props.submitLabel ?? t("Submit")}
</Button>
</div>
</Provider>
</DraftSection>
Expand Down
Loading