UserPicker.tsx 1.7 KB

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