Files
bodyshop/client/src/components/owner-search-select/owner-search-select.component.jsx
2021-01-19 09:34:43 -08:00

97 lines
2.7 KiB
JavaScript

import { LoadingOutlined } from "@ant-design/icons";
import { useLazyQuery } from "@apollo/react-hooks";
import { Empty, Select } from "antd";
import _ from "lodash";
import React, { forwardRef, useEffect, useState } from "react";
import {
SEARCH_OWNERS_BY_ID_FOR_AUTOCOMPLETE,
SEARCH_OWNERS_FOR_AUTOCOMPLETE
} from "../../graphql/owners.queries";
import AlertComponent from "../alert/alert.component";
const { Option } = Select;
const OwnerSearchSelect = ({ value, onChange, onBlur, disabled }, ref) => {
const [callSearch, { loading, error, data }] = useLazyQuery(
SEARCH_OWNERS_FOR_AUTOCOMPLETE
);
const [
callIdSearch,
{ loading: idLoading, error: idError, data: idData },
] = useLazyQuery(SEARCH_OWNERS_BY_ID_FOR_AUTOCOMPLETE);
const executeSearch = (v) => {
callSearch(v);
};
const debouncedExecuteSearch = _.debounce(executeSearch, 500);
const handleSearch = (value) => {
debouncedExecuteSearch({ variables: { 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 && idData.owners_by_pk ? [idData.owners_by_pk] : []),
...(data && data.search_owners ? data.search_owners : []),
];
return (
<div>
<Select
ref={ref}
disabled={disabled}
showSearch
autoFocus
value={option}
style={{
width: "100%",
}}
filterOption={false}
onSearch={handleSearch}
// onChange={setOption}
onChange={handleSelect}
onSelect={handleSelect}
notFoundContent={loading ? <LoadingOutlined /> : <Empty />}
onBlur={onBlur}
>
{theOptions
? theOptions.map((o) => (
<Option key={o.id} value={o.id}>
{`${o.ownr_ln || ""} ${o.ownr_fn || ""} ${
o.ownr_co_nm ? ` ${o.ownr_co_num}` : ""
}| ${o.ownr_addr1 || ""} `}
</Option>
))
: null}
</Select>
{idLoading || loading ? <LoadingOutlined /> : null}
{error ? <AlertComponent message={error.message} type="error" /> : null}
{idError ? (
<AlertComponent message={idError.message} type="error" />
) : null}
</div>
);
};
export default forwardRef(OwnerSearchSelect);