{"id":866,"date":"2020-03-25T14:32:33","date_gmt":"2020-03-25T14:32:33","guid":{"rendered":"http:\/\/www.andreagirardi.it\/blog\/?p=866"},"modified":"2020-03-26T12:00:22","modified_gmt":"2020-03-26T12:00:22","slug":"fill-options-of-autocomplete-with-api-results","status":"publish","type":"post","link":"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/","title":{"rendered":"React.js: fill options of Autocomplete with API results"},"content":{"rendered":"\n<p>The autocomplete is a normal text input enhanced by a panel of suggested options. &nbsp;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.<\/p>\n\n\n\n<p>In this case, I fill the Autocomplete with the results of Google Ads locations an this is the expected result:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"634\" height=\"610\" src=\"http:\/\/www.andreagirardi.it\/blog\/wp-content\/uploads\/2020\/03\/Screenshot-2020-03-25-at-15.28.26.png\" alt=\"\" class=\"wp-image-867\" srcset=\"https:\/\/www.andreagirardi.it\/blog\/wp-content\/uploads\/2020\/03\/Screenshot-2020-03-25-at-15.28.26.png 634w, https:\/\/www.andreagirardi.it\/blog\/wp-content\/uploads\/2020\/03\/Screenshot-2020-03-25-at-15.28.26-300x289.png 300w\" sizes=\"(max-width: 634px) 100vw, 634px\" \/><\/figure>\n\n\n\n<p>For first, import Autocomplete component (of course must be installed):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">import Autocomplete from '@material-ui\/lab\/Autocomplete';\n\/\/ or\nimport { Autocomplete } from '@material-ui\/lab';<\/code><\/pre>\n\n\n\n<p>Define the object that will be used to collect the Autocomplete options:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">const locationResults = [];<\/code><\/pre>\n\n\n\n<p>This is how Autocomplete is defined:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">let autocompleteBox = &lt;Grid item xs={12} md={12} sm={12} lg={12}>\n    &lt;Autocomplete\n        id=\"autocompleteLocations\"\n        value={this.state.autocompleteValue}\n        options={locationResults} \n        getOptionLabel={option => option.locationName}      \n        autoHighlight={true}   \n        autoSelect={true}                    \n        style={{ width: 600, marginTop: 20 }}                        \n        clearOnEscape                        \n        onChange={(event, autocompleteValue) => this.setState({ autocompleteValue })}\n        renderInput={params => &lt;TextField {...params} label=\"Search location\" variant=\"outlined\" onChange={this.handleAutocompleteTextChange.bind(this)} \/>}\n    \/>\n\n    &lt;\/Grid>;<\/code><\/pre>\n\n\n\n<p>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):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">\/**\n * On change text of Autocomplete\n *\/\nhandleAutocompleteTextChange = (event) => {\n\n    this.setState({\n        query: event.target.value\n    }, () => {\n\n        if (this.state.query &amp;&amp; this.state.query.length > 3) {\n            this.getLocations(this.state.query);\n        }\n    })\n}<\/code><\/pre>\n\n\n\n<p>This is how the function getLocations() is implemented:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">\/*\n * API Function to retrieve locations\n *\/\ngetLocations = (locationQuery) => {\n\n    axios(\n        {\n            method : 'get', url: GET_LOCATIONS, auth: this.state.userInfo.apiAuth, params: {\n            user: this.state.userInfo.username,\n            customerId: this.state.clientCustomerId,\n            query: locationQuery\n        }\n    }).then(res => {\n\n        if (res.status == 200) {\n            this.setState({results: res},()=>{\n                this.forceReloadOrganization(res)\n            });\n        } else {\n            this.setState({results: []});\n        }\n\n    }).catch(error => {\n        this.setState({results: []});\n        console.log(JSON.stringify(error));\n    });\n\n}<\/code><\/pre>\n\n\n\n<p>The last thing is to update the options on Autocomplete:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"jsx\" class=\"language-jsx\">\/**\n * Reload the results after API call\n *\/\nforceReloadOrganization = (results) => {\n    {\n\n        if ( results.data != \"\" ) {\n            results.data.map(item => {\n\n                locationResults.push({\n                        id:item.location.id,\n                        type: item.location.displayType,\n                        locationName:item.canonicalName + \": \" + item.location.displayType + \" (\" + item.location.id + \")\"\n                    }\n                )\n            });\n        }\n\n    }\n}<\/code><\/pre>\n<div class=\"sharedaddy sd-sharing-enabled\"><div class=\"robots-nocontent sd-block sd-social sd-social-icon-text sd-sharing\"><h3 class=\"sd-title\">Share this:<\/h3><div class=\"sd-content\"><ul><li class=\"share-linkedin\"><a rel=\"nofollow\" data-shared=\"sharing-linkedin-866\" class=\"share-linkedin sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=linkedin\" target=\"_blank\" title=\"Click to share on LinkedIn\"><span>LinkedIn<\/span><\/a><\/li><li class=\"share-reddit\"><a rel=\"nofollow\" data-shared=\"\" class=\"share-reddit sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=reddit\" target=\"_blank\" title=\"Click to share on Reddit\"><span>Reddit<\/span><\/a><\/li><li class=\"share-twitter\"><a rel=\"nofollow\" data-shared=\"sharing-twitter-866\" class=\"share-twitter sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=twitter\" target=\"_blank\" title=\"Click to share on Twitter\"><span>Twitter<\/span><\/a><\/li><li class=\"share-facebook\"><a rel=\"nofollow\" data-shared=\"sharing-facebook-866\" class=\"share-facebook sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=facebook\" target=\"_blank\" title=\"Click to share on Facebook\"><span>Facebook<\/span><\/a><\/li><li class=\"share-skype\"><a rel=\"nofollow\" data-shared=\"sharing-skype-866\" class=\"share-skype sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=skype\" target=\"_blank\" title=\"Share on Skype\"><span>Skype<\/span><\/a><\/li><li class=\"share-pocket\"><a rel=\"nofollow\" data-shared=\"\" class=\"share-pocket sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=pocket\" target=\"_blank\" title=\"Click to share on Pocket\"><span>Pocket<\/span><\/a><\/li><li class=\"share-end\"><\/li><\/ul><\/div><\/div><\/div>","protected":false},"excerpt":{"rendered":"<p>The autocomplete is a normal text input enhanced by a panel of suggested options. &nbsp;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 [&hellip;]<\/p>\n<div class=\"sharedaddy sd-sharing-enabled\"><div class=\"robots-nocontent sd-block sd-social sd-social-icon-text sd-sharing\"><h3 class=\"sd-title\">Share this:<\/h3><div class=\"sd-content\"><ul><li class=\"share-linkedin\"><a rel=\"nofollow\" data-shared=\"sharing-linkedin-866\" class=\"share-linkedin sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=linkedin\" target=\"_blank\" title=\"Click to share on LinkedIn\"><span>LinkedIn<\/span><\/a><\/li><li class=\"share-reddit\"><a rel=\"nofollow\" data-shared=\"\" class=\"share-reddit sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=reddit\" target=\"_blank\" title=\"Click to share on Reddit\"><span>Reddit<\/span><\/a><\/li><li class=\"share-twitter\"><a rel=\"nofollow\" data-shared=\"sharing-twitter-866\" class=\"share-twitter sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=twitter\" target=\"_blank\" title=\"Click to share on Twitter\"><span>Twitter<\/span><\/a><\/li><li class=\"share-facebook\"><a rel=\"nofollow\" data-shared=\"sharing-facebook-866\" class=\"share-facebook sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=facebook\" target=\"_blank\" title=\"Click to share on Facebook\"><span>Facebook<\/span><\/a><\/li><li class=\"share-skype\"><a rel=\"nofollow\" data-shared=\"sharing-skype-866\" class=\"share-skype sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=skype\" target=\"_blank\" title=\"Share on Skype\"><span>Skype<\/span><\/a><\/li><li class=\"share-pocket\"><a rel=\"nofollow\" data-shared=\"\" class=\"share-pocket sd-button share-icon\" href=\"https:\/\/www.andreagirardi.it\/blog\/fill-options-of-autocomplete-with-api-results\/?share=pocket\" target=\"_blank\" title=\"Click to share on Pocket\"><span>Pocket<\/span><\/a><\/li><li class=\"share-end\"><\/li><\/ul><\/div><\/div><\/div>","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"footnotes":""},"categories":[14],"tags":[20,68],"_links":{"self":[{"href":"https:\/\/www.andreagirardi.it\/blog\/wp-json\/wp\/v2\/posts\/866"}],"collection":[{"href":"https:\/\/www.andreagirardi.it\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.andreagirardi.it\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.andreagirardi.it\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.andreagirardi.it\/blog\/wp-json\/wp\/v2\/comments?post=866"}],"version-history":[{"count":4,"href":"https:\/\/www.andreagirardi.it\/blog\/wp-json\/wp\/v2\/posts\/866\/revisions"}],"predecessor-version":[{"id":871,"href":"https:\/\/www.andreagirardi.it\/blog\/wp-json\/wp\/v2\/posts\/866\/revisions\/871"}],"wp:attachment":[{"href":"https:\/\/www.andreagirardi.it\/blog\/wp-json\/wp\/v2\/media?parent=866"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.andreagirardi.it\/blog\/wp-json\/wp\/v2\/categories?post=866"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.andreagirardi.it\/blog\/wp-json\/wp\/v2\/tags?post=866"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}