all files / src/components/ AsyncSelect.jsx

93.55% Statements 29/31
77.78% Branches 7/9
77.78% Functions 7/9
93.55% Lines 29/31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81                                                                         16×                                
import React from 'react';
import PropTypes from 'prop-types';
import Select from 'react-select';
import { t } from '../locales';
 
const $ = window.$ = require('jquery');
 
const propTypes = {
  dataEndpoint: PropTypes.string.isRequired,
  onChange: PropTypes.func.isRequired,
  mutator: PropTypes.func.isRequired,
  onAsyncError: PropTypes.func,
  value: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.arrayOf(PropTypes.number),
  ]),
  valueRenderer: PropTypes.func,
  placeholder: PropTypes.string,
  autoSelect: PropTypes.bool,
};
 
const defaultProps = {
  placeholder: t('Select ...'),
  valueRenderer: o => (<div>{o.label}</div>),
  onAsyncError: () => {},
};
 
class AsyncSelect extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      options: [],
    };
  }
  componentDidMount() {
    this.fetchOptions();
  }
  onChange(opt) {
    this.props.onChange(opt);
  }
  fetchOptions() {
    this.setState({ isLoading: true });
    const mutator = this.props.mutator;
    $.get(this.props.dataEndpoint)
      .done((data) => {
        this.setState({ options: mutator ? mutator(data) : data, isLoading: false });
 
        if (!this.props.value && this.props.autoSelect && this.state.options.length) {
          this.onChange(this.state.options[0]);
        }
      })
      .fail((xhr) => {
        this.props.onAsyncError(xhr.responseText);
      })
      .always(() => {
        this.setState({ isLoading: false });
      });
  }
  render() {
    return (
      <div>
        <Select
          placeholder={this.props.placeholder}
          options={this.state.options}
          value={this.props.value}
          isLoading={this.state.isLoading}
          onChange={this.onChange.bind(this)}
          valueRenderer={this.props.valueRenderer}
          {...this.props}
        />
      </div>
    );
  }
}
 
AsyncSelect.propTypes = propTypes;
AsyncSelect.defaultProps = defaultProps;
 
export default AsyncSelect;