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-16 20:23:24 +00:00
|
|
|
const [ databases, setDatabases ] = useState<Database[] | null>(null);
|
2021-02-05 16:44:31 +00:00
|
|
|
|
|
|
|
const onSearch = (query: string): Promise<void> => {
|
|
|
|
return new Promise((resolve, reject) => {
|
2021-07-25 21:51:39 +00:00
|
|
|
searchDatabases({ name: query })
|
|
|
|
.then(databases => {
|
|
|
|
setDatabases(databases);
|
|
|
|
return resolve();
|
|
|
|
})
|
|
|
|
.catch(reject);
|
2021-02-05 16:44:31 +00:00
|
|
|
});
|
|
|
|
};
|
|
|
|
|
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-07-25 21:51:39 +00:00
|
|
|
const getSelectedText = (database: Database | null): string | undefined => {
|
|
|
|
return database?.name;
|
2021-02-16 01:48:10 +00:00
|
|
|
};
|
|
|
|
|
2021-02-05 16:44:31 +00:00
|
|
|
return (
|
|
|
|
<SearchableSelect
|
2021-07-25 21:51:39 +00:00
|
|
|
id={'databaseId'}
|
|
|
|
name={'databaseId'}
|
2021-09-13 03:22:33 +00:00
|
|
|
label={'Database Host'}
|
|
|
|
placeholder={'Select a database host...'}
|
2021-02-05 16:44:31 +00:00
|
|
|
items={databases}
|
2021-02-16 01:48:10 +00:00
|
|
|
selected={database}
|
2021-02-17 22:17:37 +00:00
|
|
|
setSelected={setDatabase}
|
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
|
|
|
|
>
|
2021-02-16 20:23:24 +00:00
|
|
|
{databases?.map(d => (
|
2021-07-25 21:51:39 +00:00
|
|
|
<Option key={d.id} selectId={'databaseId'} 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>
|
|
|
|
);
|
|
|
|
};
|