简体   繁体   中英

Using react-select Async with loadOptions and redux-form

I'm using react-select library to display a select box. I'm using Select.Async because I need to pull my options from an API. I use Select with loadOptions and it works during the intial page render. However, I'm also using redux-form which can change the value of a Field dynamically (using change ). However, when I change the value of the Field like this, the value of the input does change (and I can verify this), but react-select's loadOptions is never called again (even though I thought it was supposed to be listening to a change of value). My question is, is there a way to dynamicaly call loadOptions every time the input value changes?

Thanks,

Edit: Answered on github here

It might be a better solution than this, but a quick one is to set a ref to your Select.Async component, and when a change action is triggered (like the change of an input - your case, or one button click event - like in the code below) you can update its options. I'm using a similar example with the example of their docs.

class YourClass extends React.Component {

  getOptions = (input, callback) => {
    setTimeout(function () {
      callback(null, {
        options: [
          {value: 'one', label: 'One'},
          {value: 'two', label: 'Two'}
        ]
       });
     }, 500);
   };   

  updateOptions = () => {
    this.selectAsync.state.options.push(
      {value: 'three', label: 'Three'}
    )
  }

  render() {
    let props = this.props;

    return (
      <div>
        <Select.Async
          ref={selectAsync => this.selectAsync = selectAsync}
          loadOptions={this.getOptions}
        />
        <button onClick={this.updateOptions}>
          Load more items
        </button>
      </div>
    )
  }
}

 this.state = { store: '', }; this.handleStoreSelect = this.handleStoreSelect.bind(this); handleStoreSelect = (item) => { this.setState({ store: item.value } }; <Select.Async name="storeID" value={this.state.store} loadOptions={getStores} onChange={this.handleStoreSelect} /> 

 const getStores = () => { return fetch( "api to be hit", { method: 'get', headers: { 'Content-Type': 'application/json' } } ) .then(response => { if(response.status >= 400){ throw new Error("error"); } return response.json() }) .then(stores => { let ret = []; for(let store of stores) { ret.push({value: store._id, label: store.name}) } return {options: ret}; }) .catch(err => { console.log('could not fetch data'); console.log(err); return {options: []} }) }; 

Using this we can fetch the data and pass this object in the loadoptions. copy this code outside the class. and also i'm posting the code to be implemented for loadoptions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM