fix(customers): improve form field binding in assign to company modal
- Remove unused FormErrorMessages import - Add watch and setValue hooks from useForm for better form state management - Implement useEffect to properly initialize company_ids field with default values - Replace register-based validation with controlled component pattern - Move onChange handler from register to Select component onChange prop - Add selectedCompanyId state tracking using watch hook - Change required validation from register config to component prop - Improve form field synchronization between react-hook-form and component state
This commit is contained in:
@@ -2,7 +2,6 @@ import { Dispatch, FC, SetStateAction, useEffect, useState } from "react";
|
||||
|
||||
import { Select } from "@/components/FormElements/select";
|
||||
import { Building } from "@/components/Layouts/sidebar/icons";
|
||||
import { FormErrorMessages } from "@/constants/Texts";
|
||||
import { useCompanyFullList } from "@/hooks/queries";
|
||||
import { TAssignCustomerToCompanyCredentials } from "@/lib/api";
|
||||
import { ILabelValue } from "@/types/shared";
|
||||
@@ -21,12 +20,14 @@ const AssignToCompanyModalContent: FC<IProps> = ({
|
||||
const [options, setOptions] = useState<ILabelValue[]>([]);
|
||||
|
||||
const { data, status, isSuccess } = useCompanyFullList();
|
||||
const { handleSubmit, register } =
|
||||
const { handleSubmit, register, watch, setValue } =
|
||||
useForm<TAssignCustomerToCompanyCredentials>({
|
||||
mode: "onChange",
|
||||
defaultValues,
|
||||
});
|
||||
|
||||
const selectedCompanyId = watch("company_ids")?.[0] || "";
|
||||
|
||||
useEffect(() => {
|
||||
if (isSuccess) {
|
||||
setOptions(
|
||||
@@ -40,25 +41,31 @@ const AssignToCompanyModalContent: FC<IProps> = ({
|
||||
}
|
||||
}, [status, isSuccess, data?.data.companies]);
|
||||
|
||||
useEffect(() => {
|
||||
if (defaultValues?.company_ids?.[0]) {
|
||||
setValue("company_ids", defaultValues.company_ids);
|
||||
}
|
||||
}, [defaultValues, setValue]);
|
||||
|
||||
const assignCompany = (data: TAssignCustomerToCompanyCredentials) => {
|
||||
setCompanies(data);
|
||||
};
|
||||
return (
|
||||
<form className="mt-5" onSubmit={handleSubmit(assignCompany)}>
|
||||
<Select
|
||||
{...register("company_ids", {
|
||||
required: { message: FormErrorMessages.required, value: true },
|
||||
onChange: (e) => {
|
||||
setCompanies({
|
||||
company_ids: [e.target.value],
|
||||
});
|
||||
},
|
||||
})}
|
||||
name="company_ids"
|
||||
label="Companies"
|
||||
items={options}
|
||||
prefixIcon={<Building />}
|
||||
placeholder="Please Select company"
|
||||
value={selectedCompanyId}
|
||||
onChange={(e) => {
|
||||
setValue("company_ids", [e.target.value]);
|
||||
setCompanies({
|
||||
company_ids: [e.target.value],
|
||||
});
|
||||
}}
|
||||
required
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user