[solved] Dynamic loading data with select2

I’ve a collection called tags with 4000+ unique documents. These tags are being used to classify items.

This is the current workflow

  1. User selects an item.
  2. User clicks on a button called assign tags
  3. It will open up a modal - here, onCreated I’m fetching tags using reactive method. which are being loaded into select2. (This 3rd step takes few seconds )

Very roughly, this is what my modal looks like.

// item_tag_modal.js
import { Tags } from '../../../api/tags/tags.js';

Template.item_tag_modal.onCreated(function () {
  let instance = this;
  instance.tags = new ReactiveVar();
  instance.processing = new ReactiveVar(false);
  this.autorun(function(){
    const  result = ReactiveMethod.call("tags.available"); 
    console.log(result.count()); // 4122

     tags = result.map(function(t){
         return { id:t._id , text:t.title };
     });
     instance.tags.set(tags);
  });
});

Template.item_tag_modal.onRendered(function () {
  let instance = this;

  Meteor.setTimeout(function() {
    let tags = instance.tags.get();
    $(".tag-list").select2({
      data: tags,
      placeholder: 'Tags',
      multiple: true,
    });
  }, 900);
});

Each time fetching of 4000+ documents seems immoral to me. are there any better ways of doing it?

P.S. working with a legacy code here.

I agree with you that loading 4000 documents for the purpose of populating a select element, for the purpose of selecting tags is a bit inefficient.

Scrolling such a long list is almost never going to happen, so what’s left of the benefit Select2 offers is the search. Thus you might as well employ something similar to Twitter’s old Typeahead library: populate a drop-down as the user types.

1 Like

Maybe this is solved, but I have a collection of 25000 addresses, and I tried something similar. I ended up, instead using a variable passed to the publication, to limit my results back to 20 at a time.

I use a package that gives the functionality like twitter and the @ symbol (here as well) where it gives you options based on a key provided like ‘@’. The package mizzao:autocomplete allows the user to start typing. I then watch an event on the keyup, and when 3 characters have been entered, I pass that to my publish query, and publish back 20 addresses that match based on a regex search. This makes things load fast, because nothing is added to my options list until I get at least 3 characters from the user. As they continue to type, the list is filtered very quickly.

1 Like