2021-02-05 16:44:31 +00:00
|
|
|
import React, { useState } from 'react';
|
2021-02-16 20:03:14 +00:00
|
|
|
import { useFormikContext } from 'formik';
|
2021-02-05 16:44:31 +00:00
|
|
|
import { Database } from '@/api/admin/databases/getDatabases';
|
2021-02-16 05:41:19 +00:00
|
|
|
import searchDatabases from '@/api/admin/databases/searchDatabases';
|
|
|
|
import SearchableSelect, { Option } from '@/components/elements/SearchableSelect';
|
2021-02-05 16:44:31 +00:00
|
|
|
|
2021-02-16 05:41:19 +00:00
|
|
|
export default ({ selected }: { selected: Database | null }) => {
|
2021-02-16 20:03:14 +00:00
|
|
|
const context = useFormikContext();
|
|
|
|
|
2021-02-16 05:41:19 +00:00
|
|
|
const [ database, setDatabase ] = useState<Database | null>(selected);
|
2021-02-05 16:44:31 +00:00
|
|
|
const [ databases, setDatabases ] = useState<Database[]>([]);
|
|
|
|
|
|
|
|
const onSearch = (query: string): Promise<void> => {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
searchDatabases({ name: query }).then((databases) => {
|
|
|
|
setDatabases(databases);
|
|
|
|
return resolve();
|
|
|
|
}).catch(reject);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2021-02-16 20:03:14 +00:00
|
|
|
const onSelect = (database: Database | null) => {
|
2021-02-05 16:44:31 +00:00
|
|
|
setDatabase(database);
|
2021-02-16 20:03:14 +00:00
|
|
|
context.setFieldValue('databaseHostId', database?.id || null);
|
2021-02-05 16:44:31 +00:00
|
|
|
};
|
|
|
|
|
2021-02-16 01:48:10 +00:00
|
|
|
const getSelectedText = (database: Database | null): string => {
|
|
|
|
return database?.name || '';
|
|
|
|
};
|
|
|
|
|
2021-02-05 16:44:31 +00:00
|
|
|
return (
|
|
|
|
<SearchableSelect
|
|
|
|
id="database"
|
|
|
|
name="Database"
|
|
|
|
items={databases}
|
2021-02-16 01:48:10 +00:00
|
|
|
selected={database}
|
2021-02-05 16:44:31 +00:00
|
|
|
setItems={setDatabases}
|
|
|
|
onSearch={onSearch}
|
|
|
|
onSelect={onSelect}
|
2021-02-16 01:48:10 +00:00
|
|
|
getSelectedText={getSelectedText}
|
2021-02-05 16:44:31 +00:00
|
|
|
nullable
|
|
|
|
>
|
|
|
|
{databases.map(d => (
|
2021-02-16 05:41:19 +00:00
|
|
|
<Option key={d.id} selectId="database" id={d.id} item={d} active={d.id === database?.id}>
|
2021-02-16 01:48:10 +00:00
|
|
|
{d.name}
|
|
|
|
</Option>
|
2021-02-05 16:44:31 +00:00
|
|
|
))}
|
|
|
|
</SearchableSelect>
|
|
|
|
);
|
|
|
|
};
|