UserPicker.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import React, { Component } from 'react';
  2. import Select from 'react-select';
  3. import PickerOption from './PickerOption';
  4. import { debounce } from 'lodash';
  5. import { getBackendSrv } from 'app/core/services/backend_srv';
  6. import { User } from 'app/types';
  7. export interface Props {
  8. onSelected: (user: User) => void;
  9. value?: string;
  10. className?: string;
  11. }
  12. export interface State {
  13. isLoading: boolean;
  14. }
  15. export class UserPicker extends Component<Props, State> {
  16. debouncedSearch: any;
  17. constructor(props) {
  18. super(props);
  19. this.state = { isLoading: false };
  20. this.search = this.search.bind(this);
  21. this.debouncedSearch = debounce(this.search, 300, {
  22. leading: true,
  23. trailing: true,
  24. });
  25. }
  26. search(query?: string) {
  27. const backendSrv = getBackendSrv();
  28. this.setState({ isLoading: true });
  29. return backendSrv
  30. .get(`/api/org/users?query=${query}&limit=10`)
  31. .then(result => {
  32. return {
  33. options: result.map(user => ({
  34. id: user.userId,
  35. label: `${user.login} - ${user.email}`,
  36. avatarUrl: user.avatarUrl,
  37. login: user.login,
  38. })),
  39. };
  40. })
  41. .finally(() => {
  42. this.setState({ isLoading: false });
  43. });
  44. }
  45. render() {
  46. const { value, className } = this.props;
  47. const { isLoading } = this.state;
  48. return (
  49. <div className="user-picker">
  50. <Select.Async
  51. valueKey="id"
  52. multi={false}
  53. labelKey="label"
  54. cache={false}
  55. isLoading={isLoading}
  56. loadOptions={this.debouncedSearch}
  57. loadingPlaceholder="Loading..."
  58. noResultsText="No users found"
  59. onChange={this.props.onSelected}
  60. className={`gf-form-input gf-form-input--form-dropdown ${className || ''}`}
  61. optionComponent={PickerOption}
  62. placeholder="Select user"
  63. value={value}
  64. autosize={true}
  65. />
  66. </div>
  67. );
  68. }
  69. }