diff --git a/src/core/components/CarCode.jsx b/src/core/components/CarCode.jsx new file mode 100644 index 0000000..503a826 --- /dev/null +++ b/src/core/components/CarCode.jsx @@ -0,0 +1,86 @@ +"use client"; + +import {Autocomplete, CircularProgress, TextField} from "@mui/material"; +import {useEffect, useState} from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import {debounce} from "@mui/material/utils"; + +const CarCode = ({carCode, setCarCode}) => { + const [inputValue, setInputValue] = useState(''); + const [options, setOptions] = useState([]); + const [loading, setLoading] = useState(false); + const requestServer = useRequest(); + + const fetchCarCodes = (inputValue, controller) => { + const debouncer = debounce((query) => { + if (query.length < 2) { + setOptions([]); + return; + } + setLoading(true); + requestServer(`car-code/api?${query}`, "get", { + requestOptions: {signal: controller.signal} + }) + .then((response) => { + setOptions(response || []); + }) + .catch(() => { + setOptions([]); + }) + .finally(() => { + setLoading(false); + }); + }, 500) + debouncer(inputValue) + } + + useEffect(() => { + const controller = new AbortController(); + fetchCarCodes(inputValue, controller); + return () => controller.abort(); + }, [inputValue]); + + return ( + { + setCarCode(newValue); + }} + inputValue={inputValue} + onInputChange={(event, newInputValue) => { + setInputValue(newInputValue); + }} + options={options} + getOptionLabel={(option) => + typeof option === 'string' ? option : option.name || option.code + } + loading={loading} + loadingText="درحال جستجوی کد خودرو" + noOptionsText={ + inputValue.length < 2 + ? "حداقل دو رقم از کد خودرو را وارد کنید" + : "کد خودرویی یافت نشد" + } + sx={{width: 300}} + renderInput={(params) => ( + + {loading ? : null} + {params.InputProps.endAdornment} + + ), + }} + /> + )} + /> + ); +}; + +export default CarCode; \ No newline at end of file