<CodeAutocomplete
label={"Код операции/Расшифровка"}
requestUrl={`${baseUrl}/view_to_name`}
codeField={"to_code"}
nameField={"to_name"}
error={!!errors.to_code}
helperText={errors.to_code}
value={
form.to_code
? {to_code: form.to_code, to_name: form.to_name}
: null
}
onChange={(val) => {
if (val) {
setForm({
...form,
to_code: val.to_code,
to_name: val.to_name,
});
} else {
setForm({
...form,
to_code: "",
to_name: "",
});
}
console.log(val.to_code)
}}
/>
import { Autocomplete, TextField } from "@mui/material";
import axios from "axios";
import { useState, useEffect } from "react";
interface CodeAutocompleteProps {
label: string;
requestUrl: string; // URL для поиска
codeField: string; // поле кода
nameField: string; // поле расшифровки
value: any; // {code, name}
onChange: (val: any) => void;
error?: boolean;
helperText?: string;
}
export default function CodeAutocomplete({
label,
requestUrl,
codeField,
nameField,
value,
onChange,
error,
helperText
}: CodeAutocompleteProps) {
const [options, setOptions] = useState([]);
const fetchOptions = async (query) => {
const res = await axios.get(`${requestUrl}?query=${query}`);
setOptions(res.data || []);
};
// debounce
let timer;
const handleInputChange = (_, inputValue) => {
clearTimeout(timer);
timer = setTimeout(() => {
if (inputValue.length >= 1) fetchOptions(inputValue);
}, 300);
};
return (
<Autocomplete
style={{marginTop: "8px"}}
options={options}
value={value ? value[nameField] : ""}
onChange={(_, newValue) => {
if (newValue) {
onChange({
[codeField]: newValue[codeField],
[nameField]: newValue[nameField],
});
} else {
onChange(null);
}
}}
getOptionLabel={(option) =>{
if (typeof option === "string") return option;
return `${option[codeField]} — ${option[nameField]}`;
}}
onInputChange={handleInputChange}
filterOptions={(x) => x}
renderInput={(params) => (
<TextField
{...params}
label={label}
error={error}
helperText={helperText}
/>
)}
fullWidth
/>
);
}