2021-02-16 05:41:19 +00:00
|
|
|
import React, { useState } from 'react';
|
2021-02-16 20:03:14 +00:00
|
|
|
import { useFormikContext } from 'formik';
|
2021-01-31 22:59:37 +00:00
|
|
|
import { Location } from '@/api/admin/locations/getLocations';
|
|
|
|
import searchLocations from '@/api/admin/locations/searchLocations';
|
2021-02-16 05:41:19 +00:00
|
|
|
import SearchableSelect, { Option } from '@/components/elements/SearchableSelect';
|
2021-01-31 22:59:37 +00:00
|
|
|
|
2021-02-16 05:41:19 +00:00
|
|
|
export default ({ selected }: { selected: Location | null }) => {
|
2021-02-16 20:03:14 +00:00
|
|
|
const context = useFormikContext();
|
|
|
|
|
2021-02-16 05:41:19 +00:00
|
|
|
const [ location, setLocation ] = useState<Location | null>(selected);
|
2021-02-16 20:23:24 +00:00
|
|
|
const [ locations, setLocations ] = useState<Location[] | null>(null);
|
2021-01-31 22:59:37 +00:00
|
|
|
|
2021-02-16 05:41:19 +00:00
|
|
|
const onSearch = (query: string): Promise<void> => {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
searchLocations({ short: query }).then((locations) => {
|
|
|
|
setLocations(locations);
|
|
|
|
return resolve();
|
|
|
|
}).catch(reject);
|
|
|
|
});
|
2021-01-31 22:59:37 +00:00
|
|
|
};
|
|
|
|
|
2021-02-16 20:03:14 +00:00
|
|
|
const onSelect = (location: Location | null) => {
|
2021-01-31 22:59:37 +00:00
|
|
|
setLocation(location);
|
2021-02-16 20:03:14 +00:00
|
|
|
context.setFieldValue('locationId', location?.id || null);
|
2021-01-31 22:59:37 +00:00
|
|
|
};
|
|
|
|
|
2021-02-16 05:41:19 +00:00
|
|
|
const getSelectedText = (location: Location | null): string => {
|
|
|
|
return location?.short || '';
|
|
|
|
};
|
2021-02-02 21:11:54 +00:00
|
|
|
|
2021-01-31 22:59:37 +00:00
|
|
|
return (
|
2021-02-16 05:41:19 +00:00
|
|
|
<SearchableSelect
|
|
|
|
id="location"
|
|
|
|
name="Location"
|
|
|
|
items={locations}
|
|
|
|
selected={location}
|
2021-02-17 22:17:37 +00:00
|
|
|
setSelected={setLocation}
|
2021-02-16 05:41:19 +00:00
|
|
|
setItems={setLocations}
|
|
|
|
onSearch={onSearch}
|
|
|
|
onSelect={onSelect}
|
|
|
|
getSelectedText={getSelectedText}
|
|
|
|
nullable
|
|
|
|
>
|
2021-02-16 20:23:24 +00:00
|
|
|
{locations?.map(d => (
|
2021-02-16 05:41:19 +00:00
|
|
|
<Option key={d.id} selectId="location" id={d.id} item={d} active={d.id === location?.id}>
|
|
|
|
{d.short}
|
|
|
|
</Option>
|
|
|
|
))}
|
|
|
|
</SearchableSelect>
|
2021-01-31 22:59:37 +00:00
|
|
|
);
|
|
|
|
};
|