axios - autocomplete
Closed this issue · 5 comments
I am wondering how do I make the list be able to be from a axios request?
I found out the hard way that you can't do this
function checkAnswer(event, e) {
if(currentTimeoutId){
clearTimeout(currentTimeoutId);
}
currentTimeoutId = setTimeout(function(){
currentTimeoutId = null;
axios.get('https://nominatim.openstreetmap.org/search.php?city='+e+'&countrycodes=AU&featuretype=county&polygon_geojson=1&format=json')
.then(function (response) {
// handle success
//alert(JSON.stringify(response.data))
console.log(response);
document.getElementById("results").innerHTML = "";
for (let i = 0; i < response.data.length; i++) {
// alert(response.data[i].osm_id)
document.getElementById("results").innerHTML +="<button onClick={addToResult("+response.data[i].osm_id+")}>ID:"+response.data[i].osm_id+" - "+response.data[i].display_name+"</button>\n\n"
}
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
//alert(response)
});
},1000);
}
@redimongo Can you please make a codesandbox example?
I have faced the similar issue. I want to send request to an api when input value change but i couldnt find any onChange event. Is there any way to search with async data ?
I think what you guys want to do is resolved in this comment: #50
I'll close this for now, but if you have still problems please create a codesandbox example.
@yanffz Hello! All you need to do is to add a handler for
onSearch
where you use something likefetch
to send the request to the API and then pass the new items to RSA. A rough example:const [items, setItems] = useState([]) const handleOnSearch = async (string, results) => { await fetch(`api/endopoint?search=${string}`) .then(response => response.json()) .then(data => setItems(data)) } // in the render method <ReactSearchAutocomplete items={items} onSearch={handleOnSearch} />
Said that, what does the first API call do? Is it searching for a string? If so, you are basically sending a search query to an endpoint, getting some results, putting them in RSA then searching again within RSA; it's a bit weird. Ideally RSA should have a single list that needs to be searched in. I think that what you need is just a normal
select
element that shows the list of items you get from the API.
const [items, setItems] = useState([])
const handleOnSearch = async (string, results) => {
await fetch(`api/endopoint?search=${string}`)
.then(response => response.json())
.then(data => setItems(data))
}
// in the render method
<ReactSearchAutocomplete
items={items}
onSearch={handleOnSearch}
/>
This code actually doesn't work because it shows the result before fetching the API response. We have to press space key to get the updated results. Is there callback function we can manually show the dropdown list?