cf3a931cef
- Add ChangeEvent import for proper TypeScript typing - Remove unused register function from useForm hook - Refactor onChange handler with explicit ChangeEvent<HTMLSelectElement> type annotation - Extract target value into variable for improved readability - Ensure consistent form field updates between setValue and setCompanies calls - Improve type safety and reduce potential runtime errors in form handling
78 lines
2.2 KiB
TypeScript
78 lines
2.2 KiB
TypeScript
import { ChangeEvent, Dispatch, FC, SetStateAction, useEffect, useState } from "react";
|
|
|
|
import { Select } from "@/components/FormElements/select";
|
|
import { Building } from "@/components/Layouts/sidebar/icons";
|
|
import { useCompanyFullList } from "@/hooks/queries";
|
|
import { TAssignCustomerToCompanyCredentials } from "@/lib/api";
|
|
import { ILabelValue } from "@/types/shared";
|
|
import { useForm } from "react-hook-form";
|
|
|
|
interface IProps {
|
|
setCompanies: Dispatch<
|
|
SetStateAction<TAssignCustomerToCompanyCredentials | undefined>
|
|
>;
|
|
defaultValues?: TAssignCustomerToCompanyCredentials;
|
|
}
|
|
const AssignToCompanyModalContent: FC<IProps> = ({
|
|
setCompanies,
|
|
defaultValues,
|
|
}) => {
|
|
const [options, setOptions] = useState<ILabelValue[]>([]);
|
|
|
|
const { data, status, isSuccess } = useCompanyFullList();
|
|
const { handleSubmit, watch, setValue } =
|
|
useForm<TAssignCustomerToCompanyCredentials>({
|
|
mode: "onChange",
|
|
defaultValues,
|
|
});
|
|
|
|
const selectedCompanyId = watch("company_ids")?.[0] || "";
|
|
|
|
useEffect(() => {
|
|
if (isSuccess) {
|
|
setOptions(
|
|
data.data.companies
|
|
? data.data.companies?.map((item) => ({
|
|
label: item.name,
|
|
value: item.id,
|
|
}))
|
|
: [],
|
|
);
|
|
}
|
|
}, [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
|
|
name="company_ids"
|
|
label="Companies"
|
|
items={options}
|
|
prefixIcon={<Building />}
|
|
placeholder="Please Select company"
|
|
value={selectedCompanyId}
|
|
onChange={
|
|
((e: ChangeEvent<HTMLSelectElement>) => {
|
|
const value = e.target.value;
|
|
setValue("company_ids", [value]);
|
|
setCompanies({
|
|
company_ids: [value],
|
|
});
|
|
}) as any
|
|
}
|
|
required
|
|
/>
|
|
</form>
|
|
);
|
|
};
|
|
|
|
export default AssignToCompanyModalContent;
|