0

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.

aelor
  • 10,892
  • 3
  • 32
  • 48
  • can you paste your code? – delis Feb 15 '19 at 12:55
  • This is what you want: https://stackoverflow.com/questions/4220126/run-javascript-function-when-user-finishes-typing-instead-of-on-key-up – Hackinet Feb 15 '19 at 13:14
  • you can instead of debouncing (that runs multiple queries) you could check a timer with setTimeout (after n seconds for example) that the timer is still active, else simply set a variable `QUERY` to `true` and in the setTimeout callback clear the timeout do the query with current select value (if `QUERY` var is `true`) and rest the timer for another n seconds. Something like that could work example https://stackoverflow.com/questions/53592232/how-to-improve-my-ajax-live-search-by-doing-less-amount-of-requests/53592921#53592921 – Nikos M. Feb 15 '19 at 13:21

1 Answers1

0

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.