Search code examples
jquerytwitter-typeahead

Twitter Typeahead - Duplicate AJAX Suggestions


I was able to use the older version of Twitter Typeahead without a problem, my knowledge of the new one is definitely limited, and I am definitely confused on why there are duplicate entries showing up.

This is my Javascript:

// Sources
var sources = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: '/sources/prefetch/',
    remote: '/sources/prefetch/'
});

sources.initialize();

$('#a_sources_list').typeahead(null, {
  name: 'sources',
  displayKey: 'name',
  source: sources.ttAdapter()
})

/sources/prefetch/ returns:

[{"id":"1","name":"Google"},{"id":"3","name":"Yahoo"}]

Here is a screenshot of what is happening:Duplicate Results


Solution

  • The issue was with both prefetch and remote being called from the same source.

    The issue is detailed here:
    https://github.com/twitter/typeahead.js/issues/614

    Essentially, BloodHound has a default limit. If the number of suggestions are under that limit, it calls the remote URL.

    There is an option to create a duplicate detector:
    https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md#options

    You can use this to make sure the same item doesn't appear twice.

    Here's an example of a dupDetector:
    https://github.com/twitter/typeahead.js/issues/606#issuecomment-34667422

    dupDetector: function(remoteMatch, localMatch) {
        return remoteMatch.id === localMatch.id;
    }