-
Notifications
You must be signed in to change notification settings - Fork 6
/
SearchLocation.tsx
86 lines (73 loc) · 2.4 KB
/
SearchLocation.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { Autocomplete, Icon } from "@bbtgnn/polaris-interfacer";
import { SearchMinor } from "@shopify/polaris-icons";
import { ProjectType, SelectOption } from "components/types";
import { FetchLocation, fetchLocation, LocationLookup, lookupLocation } from "lib/fetchLocation";
import { useTranslation } from "next-i18next";
import { useCallback, useEffect, useState } from "react";
import { PFieldInfoProps } from "./polaris/PFieldInfo";
//
export interface Props extends Partial<PFieldInfoProps> {
onSelect?: (value: LocationLookup.Location | null) => void;
excludeIDs?: Array<string>;
label?: string;
conformsTo?: Array<ProjectType>;
placeholder?: string;
id?: string;
}
export default function SearchLocation(props: Props) {
const { t } = useTranslation();
const {
onSelect = () => {},
label = t("Search for an address"),
placeholder = t("Street, number, city, country"),
id,
} = props;
/* Searching locations */
const [inputValue, setInputValue] = useState("");
const handleInputChange = useCallback((value: string) => {
setInputValue(value);
}, []);
const [options, setOptions] = useState<Array<SelectOption>>([]);
const [loading, setLoading] = useState<boolean>(false);
useEffect(() => {
const searchLocation = async () => {
setLoading(true);
setOptions(createOptionsFromResult(await fetchLocation(inputValue)));
setLoading(false);
};
searchLocation();
}, [inputValue]);
function createOptionsFromResult(result: Array<FetchLocation.Location>): Array<SelectOption> {
return result.map(location => {
return {
value: location.id,
label: location.title,
};
});
}
/* Handling selection */
async function handleSelect(selected: string[]) {
const location = await lookupLocation(selected[0]);
if (!location) onSelect(null);
else onSelect(location);
setInputValue("");
}
/* Rendering */
const textField = (
<Autocomplete.TextField
id={id}
onChange={handleInputChange}
autoComplete="off"
label={label}
value={inputValue}
error={props.error}
helpText={props.helpText}
prefix={<Icon source={SearchMinor} color="base" />}
placeholder={placeholder}
requiredIndicator={props.requiredIndicator}
/>
);
return (
<Autocomplete options={options} selected={[]} onSelect={handleSelect} loading={loading} textField={textField} />
);
}