type-ahead.js icon indicating copy to clipboard operation
type-ahead.js copied to clipboard

Race condition causes items to be added twice

Open ghost opened this issue 10 years ago • 2 comments

When populating the list from remote content, sometimes the callback passed to getCandidates gets called twice in a row so we end up with duplicated items in the list. I suppose the chance of this happening is higher when the server is a bit slow to respond, which is why you didn't notice it.

For instance I'm looking for items containing the word "house" so I decide to type the letters h, o, u and s. What's happening is that I have the time type the letter s before the request for "hou" has completed, so when the keyUp handler handles the s key the list is still empty. After I've typed s, the browser receives responses for both "hou" and "hous" and calls the callback twice with the same results, which causes them to be added twice to the list.

Adding a call to typeAhead.list.clear(); before https://github.com/marcojetson/type-ahead.js/blob/master/src/type-ahead.js#L77 seems to fix it.

ghost avatar Sep 25 '15 06:09 ghost

Clearing the list may look like a fix but the problem is that the requests are asynchronous and you cannot guarantee the order of the responses. In your example "hou" and "hous" return the same results but they may return different ones.

In your getCandidates implementation you should abort any previous request. I think the library should provide a clearer way to see this, like an onBeforeGetCandidates event or something similar.

I will also update the examples using remote.

marcojetson avatar Sep 25 '15 08:09 marcojetson

Oh right, I didn't think about that. Thanks!

ghost avatar Sep 25 '15 13:09 ghost