Tag Archives: React

React.js: fill options of Autocomplete with API results

The autocomplete is a normal text input enhanced by a panel of suggested options.  Autocomplete is a feature that helps in predicting the rest of the word typed by a user. Autocomplete is helpful from the user as well as the user experience perspective. It makes users happy by saving their time and also by offering them several choices.

In this case, I fill the Autocomplete with the results of Google Ads locations an this is the expected result:

For first, import Autocomplete component (of course must be installed):

import Autocomplete from '@material-ui/lab/Autocomplete';
// or
import { Autocomplete } from '@material-ui/lab';

Define the object that will be used to collect the Autocomplete options:

const locationResults = [];

This is how Autocomplete is defined:

let autocompleteBox = <Grid item xs={12} md={12} sm={12} lg={12}>
    <Autocomplete
        id="autocompleteLocations"
        value={this.state.autocompleteValue}
        options={locationResults} 
        getOptionLabel={option => option.locationName}      
        autoHighlight={true}   
        autoSelect={true}                    
        style={{ width: 600, marginTop: 20 }}                        
        clearOnEscape                        
        onChange={(event, autocompleteValue) => this.setState({ autocompleteValue })}
        renderInput={params => <TextField {...params} label="Search location" variant="outlined" onChange={this.handleAutocompleteTextChange.bind(this)} />}
    />

    </Grid>;

Once the user enters some text on Search location TextField, this function is called (I expect user inserts at least 3 chars before call the API):

/**
 * On change text of Autocomplete
 */
handleAutocompleteTextChange = (event) => {

    this.setState({
        query: event.target.value
    }, () => {

        if (this.state.query && this.state.query.length > 3) {
            this.getLocations(this.state.query);
        }
    })
}

This is how the function getLocations() is implemented:

/*
 * API Function to retrieve locations
 */
getLocations = (locationQuery) => {

    axios(
        {
            method : 'get', url: GET_LOCATIONS, auth: this.state.userInfo.apiAuth, params: {
            user: this.state.userInfo.username,
            customerId: this.state.clientCustomerId,
            query: locationQuery
        }
    }).then(res => {

        if (res.status == 200) {
            this.setState({results: res},()=>{
                this.forceReloadOrganization(res)
            });
        } else {
            this.setState({results: []});
        }

    }).catch(error => {
        this.setState({results: []});
        console.log(JSON.stringify(error));
    });

}

The last thing is to update the options on Autocomplete:

/**
 * Reload the results after API call
 */
forceReloadOrganization = (results) => {
    {

        if ( results.data != "" ) {
            results.data.map(item => {

                locationResults.push({
                        id:item.location.id,
                        type: item.location.displayType,
                        locationName:item.canonicalName + ": " + item.location.displayType + " (" + item.location.id + ")"
                    }
                )
            });
        }

    }
}
Tagged ,