Last Updated: September 09, 2019
·
5.374K
· benjaminrh

Showing "loading" in Meteor

If you've been playing around with Meteor, you might have noticed that collections you subscribe to can take an awfully long time to load. During that time, it would be nice to let users know that something is actually loading.

There are a number of ways you could accomplish this, but here's the easiest and most effective way I've found. Observe.

First, we setup a session variable that designates my_collection as loading. This runs right when Meteor starts up.

Meteor.startup(function() {
    Session.setDefault('my_collection_loading', true);
});

Now let's subscribe to my_collection. But wait! We set up a callback that runs when the subscription has got the data. The callback changes the session variable to false, to signify we're done loading the data.

Deps.autorun(function() {
    Meteor.subscribe('my_collection', function() {
        // This will run when we're subscribed
        Session.set('my_collection_loading', false);
    });
});

While the data's loading, let's set up a template helper for our template. It will simply return the session variable. When the data is loading, it returns true. When it's finished, it returns false. Simple stuff.

Template.foobar.helpers({
    my_collection_loading: function() {
        return Session.get('my_collection_loading');
    }
});

Finally, the template. Here we're setting up a list that simply loops through the items and displays the item name. That's the data. Below that, you'll notice a Handlebars if block helper, that will display "Loading" in big heading text. When the data finishes loading, the template helper will change to false, and the loading notice will disappear.

<template name="foobar">
    <ul>
        {{#each item}}
        <li>{{item.name}}</li>
        {{/each}}
    </ul>

    {{#if my_collection_loading}}
    <h2>Loading...</h2>
    {{/if}}
</template>

And that's it! I encourage you to try it. It makes for a much nicer user experience.