1import React, { useEffect } from 'react';
2import { AsyncSelect } from '@grafana/ui';
3import { getBackendSrv } from 'app/core/services/backend_srv';
4import { Organization } from 'app/types';
5import { SelectableValue } from '@grafana/data';
6import { useAsyncFn } from 'react-use';
7
8export type OrgSelectItem = SelectableValue<Organization>;
9
10export interface Props {
11  onSelected: (org: OrgSelectItem) => void;
12  className?: string;
13  inputId?: string;
14  autoFocus?: boolean;
15}
16
17export function OrgPicker({ onSelected, className, inputId, autoFocus }: Props) {
18  // For whatever reason the autoFocus prop doesn't seem to work
19  // with AsyncSelect, hence this workaround. Maybe fixed in a later version?
20  useEffect(() => {
21    if (autoFocus && inputId) {
22      document.getElementById(inputId)?.focus();
23    }
24  }, [autoFocus, inputId]);
25
26  const [orgOptionsState, getOrgOptions] = useAsyncFn(async () => {
27    const orgs: Organization[] = await getBackendSrv().get('/api/orgs');
28    return orgs.map((org) => ({ value: { id: org.id, name: org.name }, label: org.name }));
29  });
30
31  return (
32    <AsyncSelect
33      menuShouldPortal
34      inputId={inputId}
35      className={className}
36      isLoading={orgOptionsState.loading}
37      defaultOptions={true}
38      isSearchable={false}
39      loadOptions={getOrgOptions}
40      onChange={onSelected}
41      placeholder="Select organization"
42      noOptionsMessage="No organizations found"
43    />
44  );
45}
46