Files
bodyshop/client/src/components/vehicle-search-select/vehicle-search-select.component.jsx
2026-02-02 16:44:49 -05:00

92 lines
2.6 KiB
JavaScript

import { LoadingOutlined } from "@ant-design/icons";
import { useLazyQuery } from "@apollo/client/react";
import { Empty, Select } from "antd";
import _ from "lodash";
import { useEffect, useState } from "react";
import {
SEARCH_VEHICLES_BY_ID_FOR_AUTOCOMPLETE,
SEARCH_VEHICLES_FOR_AUTOCOMPLETE
} from "../../graphql/vehicles.queries";
import AlertComponent from "../alert/alert.component";
const { Option } = Select;
const VehicleSearchSelect = ({ value, onChange, onBlur, disabled, ref }) => {
const [callSearch, { loading, error, data }] = useLazyQuery(SEARCH_VEHICLES_FOR_AUTOCOMPLETE);
const [callIdSearch, { loading: idLoading, error: idError, data: idData }] = useLazyQuery(
SEARCH_VEHICLES_BY_ID_FOR_AUTOCOMPLETE
);
const executeSearch = (variables) => {
if (variables?.search !== "" && variables?.search?.length >= 2) callSearch({ variables });
};
const debouncedExecuteSearch = _.debounce(executeSearch, 500);
const handleSearch = (value) => {
debouncedExecuteSearch({ search: value });
};
const [option, setOption] = useState(value);
useEffect(() => {
if (value === option && value) {
callIdSearch({ variables: { id: value } });
}
}, [value, option, callIdSearch]);
// useEffect(() => {
// if (value !== option && onChange) {
// onChange(option);
// }
// }, [value, option, onChange]);
const handleSelect = (value) => {
setOption(value);
if (value !== option && onChange) {
onChange(value);
}
};
const theOptions = [
...(idData?.vehicles_by_pk ? [idData.vehicles_by_pk] : []),
...(data?.search_vehicles ? data.search_vehicles : [])
];
return (
<div>
<Select
ref={ref}
disabled={disabled}
showSearch={{
filterOption: false,
onSearch: handleSearch
}}
autoFocus
value={option}
style={{
width: "100%"
}}
// onChange={setOption}
onChange={handleSelect}
onSelect={handleSelect}
notFoundContent={loading ? <LoadingOutlined /> : <Empty />}
onBlur={onBlur}
>
{theOptions
? theOptions.map((o) => (
<Option key={o.id} value={o.id}>
{`${o.v_vin || ""} ${o.v_model_yr || ""} ${o.v_make_desc || ""} ${o.v_model_desc || ""} `}
</Option>
))
: null}
</Select>
{idLoading || loading ? <LoadingOutlined /> : null}
{error ? <AlertComponent title={error.message} type="error" /> : null}
{idError ? <AlertComponent title={idError.message} type="error" /> : null}
</div>
);
};
export default VehicleSearchSelect;