Avi Kaminetzky
Avi Kaminetzky

Reputation: 1538

React Select with Async - Failing to load options

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.

enter image description here

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}
/>

Upvotes: 5

Views: 6580

Answers (1)

Doron Brikman
Doron Brikman

Reputation: 2584

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 }
            })
    }

Upvotes: 7

Related Questions