-->

React Select with Async - Failing to load options

2019-07-06 08:15发布

问题:

I am attempting to create a react-select async input field that provides model numbers based on user input. My API is working, as is the Fetch, which is producing the exact 'options' object required to populate dropdown (I checked both the network requests and the console).

The problem is that when I start typing, the dropdown shows that it is loading, but no options are added to it.

Here is an example output from the Fetch call: {options: [{value: "WA501006", label: "WA501006"}]}.

This is my code:

getModelsAPI = (input) => {

        if (!input) {
            return Promise.resolve({ options: [] });
        }

        const url = `(...)?cmd=item_codes_json&term=${input}`;

        fetch(url, {credentials: 'include'})
            .then((response) => {
                return response.json();
            })
            .then((json) => {
                const formatted = json.map((l) => {
                    return Object.assign({}, {
                        value: l.value,
                        label: l.label
                    });
                })
                return { options: formatted }
            })
    }

onChange = (value) => {
    this.setState({
        value: value
    })
}

<Select.Async
  value={this.state.value}
  loadOptions={this.getModelsAPI}
  placeholder="Enter Model"
  onChange={this.onChange}
/>

回答1:

I think you need to return from the getModelsAPI function:

getModelsAPI = (input) => {

        if (!input) {
            return Promise.resolve({ options: [] });
        }

        const url = `(...)?cmd=item_codes_json&term=${input}`;

        return fetch(url, {credentials: 'include'})
            .then((response) => {
                return response.json();
            })
            .then((json) => {
                const formatted = json.map((l) => {
                    return Object.assign({}, {
                        value: l.value,
                        label: l.label
                    });
                })
                return { options: formatted }
            })
    }