1👍
✅
Recipe: any HTTP client(with/without cancellable HTTP client), denounce function(lodash has good one), CSS design the suits displaying your results in.
Here is the basic idea
You create a denounced function and get an instance of that function that can be cancelled, so every time the user hit the search bar we cancel the old subscriptions to that function and resubscribe with new denounced timeout, when that timeout ends we call the function to hit the API and get the response(which represent the autocomplete response) to be display as you like.
import React, { useState } from 'react';
import axios from 'axios';
import { debounce } from 'lodash';
let debouncedFunction: any;
function App() {
const [inputValue, setInputValue] = useState('');
const onSearchChange = (event: any) => {
try {
setInputValue(event.target.value);
/**
* cancel old saved debounced functions
*/
if (debouncedFunction && debouncedFunction.cancel)
debouncedFunction.cancel();
debouncedFunction = debounce(async () => {
// use event value if you want in request
const response: any = await axios.get(
'https://jsonplaceholder.typicode.com/todos/1' + `?test=${event.target.value}`
);
if (response.data) {
console.log('autocomplete results...')
}
}, 2000);
debouncedFunction();
} catch (error) {
console.error(error);
}
}
return (
<div >
<input
value={inputValue}
onChange={onSearchChange}
placeholder="Search with autocomplete..."
/>
</div>
);
}
export default App;
The rest of displaying the autocomplete results is left for your app to display what better suits you
here is a link to the repo to download and tweak as you like
Source:stackexchange.com