All files / javascripts/components AsyncSelect.jsx

89.47% Statements 17/19
25% Branches 1/4
50% Functions 2/4
94.44% Lines 17/18
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 601x 1x 1x   1x                 1x   1x       9x   3x           1x   1x 1x 1x 1x         1x     4x                             1x 1x      
const $ = window.$ = require('jquery');
import React from 'react';
import Select from 'react-select';
 
const propTypes = {
  dataEndpoint: React.PropTypes.string.isRequired,
  onChange: React.PropTypes.func.isRequired,
  mutator: React.PropTypes.func.isRequired,
  value: React.PropTypes.number,
  valueRenderer: React.PropTypes.func,
  placeholder: React.PropTypes.string,
};
 
const defaultProps = {
  placeholder: 'Select ...',
  valueRenderer: (o) => (<div>{o.label}</div>),
};
 
class AsyncSelect extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      options: [],
    };
  }
  componentDidMount() {
    this.fetchOptions();
  }
  fetchOptions() {
    this.setState({ isLoading: true });
    const mutator = this.props.mutator;
    $.get(this.props.dataEndpoint, (data) => {
      this.setState({ options: mutator ? mutator(data) : data, isLoading: false });
    });
  }
  onChange(opt) {
    this.props.onChange(opt);
  }
  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}
        />
      </div>
    );
  }
}
 
AsyncSelect.propTypes = propTypes;
AsyncSelect.defaultProps = defaultProps;
 
export default AsyncSelect;