There is an input box with custom built autocomplete. I make api calls to the server based on whats entered in the input box onkeyup. However that leads to lot of api calls as it happens on every character entered. Instead I would like to make api calls only after the user has entered and waited.
I used debounce from lodash. Which waits for the user to stop typing before making a call. But when it does, it makes multiple calls
Suppose i entered "Berlin" I will end up with 6 ajax calls(B, BE, BER, BERL, BERLI, BERLIN) after the debouce timeout gets over. Ideally there should have been only one api call with BERLIN as the user stopped typing after entering that much.
I dont know how much the code will make sense here. But I will still paste it
fetchConsigneeDetail = async (searchStr) => {
if (!searchStr) return
const param = {
customerName: this.state.assoCompany.text,
text: searchStr,
type: 'CODE'
}
let data = await ADD_TRIP_API.getConsigneeDetails(param)
this.setState({ consigneeArr: data })
}
<Select
allowClear
showSearch
size="large"
placeholder="e.g KA56AB122"
onSearch={input => {
const debounceCalculate = _.debounce(this.fetchConsigneeDetail, 1300);
debounceCalculate(input);
}}
}
onChange={this.selectConsignee}
>
{consigneeArr &&
consigneeArr.length > 0 &&
consigneeArr.map((data, index) => (
<Option key={index} value={data.code}>
{data.code}
</Option>
))}
</Select>
The ADD_TRIP_API.getConsigneeDetails(param)
does the api call. Normal axios call, nothing fancy there.