TeamPicker.tsx 1.7 KB

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