import { Autocomplete, TextField } from "@mui/material"; import { useRef, useState, useEffect } from "react"; function AutoComplete({ data, noneBg, clearText, inputValue, // مقدار کنترل‌شده از والد (اختیاری) placeholder, handleSearch, // تابعی که باید با مقدار جستجو صدا زده بشه setInputValue, // اختیاری: اگه والد دوست داره همون‌وقت مقدار رو بگیره setSelectedOption, debounce = 500, // قابل تنظیم }) { const typingTimeoutRef = useRef(null); const [localInput, setLocalInput] = useState(inputValue || ""); // همگام‌سازی وقتی والد مقدار کنترل‌شده رو تغییر میده (مثلاً بعد از انتخاب گزینه) useEffect(() => { setLocalInput(inputValue || ""); }, [inputValue]); // پاک‌کردن تایمر هنگام unmount useEffect(() => { return () => { if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current); }; }, []); const onInputChange = (_, newInputValue) => { // نمایش آنی تایپ کاربر setLocalInput(newInputValue); // اختیاری: اگر والد خواست همون‌جا مقدار رو بگیره if (setInputValue) setInputValue(newInputValue); // پاک کردن تایمر قبلی و ست کردن تایمر جدید برای debounce if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current); typingTimeoutRef.current = setTimeout(() => { handleSearch(newInputValue); }, debounce); }; const onChange = (_, newValue) => { // انتخاب از لیست — مقدار رو فوراً پردازش کن if (typingTimeoutRef.current) { clearTimeout(typingTimeoutRef.current); typingTimeoutRef.current = null; } const val = newValue ? typeof newValue === "string" ? newValue : newValue.name : ""; setLocalInput(val); setSelectedOption && setSelectedOption(newValue); handleSearch(val); // اجرای فوری روی انتخاب if (setInputValue) setInputValue(val); }; return ( typeof option === "string" ? option : option.name } disableClearable inputValue={localInput} // ← نمایش آنی از local state className="!w-full" onInputChange={onInputChange} onChange={onChange} renderOption={(props, option) => (
  • {option.name}
  • )} sx={{ "& .MuiAutocomplete-input": { background: noneBg ? "" : "#ffffff !important", }, }} renderInput={(params) => ( )} /> ); } export default AutoComplete;