UserPicker.tsx 2.0 KB

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