简体   繁体   中英

How to fire an ajax call in a custom autocomplete only when the user finishes typing and waits for n seconds

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.

On client side, you could use the Javascript setTimeout method. But I'm really not sure where you want to do this. Please give us more code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM