Collection find fire two times

Hello. I have app with structure like this app https://github.com/meteor/todos
Have collection of Leads:

export const Leads = new Mongo.Collection('leads', {
  _preventAutopublish: true,
});

Loading templates like this:

FlowRouter.route('/leads', {
    name: 'leads',
    action() {
        BlazeLayout.render('mainLayout', {
            content: 'leads'
        });
    }
});

In Leads template I get leads:

import './leads.html';
import { Leads } from '../../../api/leads/leads.js';

Template.leads.helpers({
    leads: function() {
        var leads = Leads.find({}, {sort: {createdAt: 1}}).fetch();

        if (leads) {
            return leads;
        }
    },
})

When I try fetch leads first time I get empty array and then array of leads. Can somebody tell me why it fire two times and how load leads after manual page refresh. Thanks beforehand.

Double execution is a side effect of reactivtiy. Template helpers establish a reactive context and reactive data sources establish a link to and invalidate reactive data contexts causing their computations to re-run.

Leads.find({}, {sort: {createdAt: 1}}).fetch(); establishes a reactive computation within helpers reactive context and returns an empty array since the data has not yet reached the client. Once data reaches the client it changes the dataset and the computation is invalidated causing the helper to run again and the query returns the new data.

On an aside, you can omit the fetch() call and just return the cursor directly since you are using blaze.

1 Like

Can you give me example? I will be very grateful.

Template.leads.helpers({
    leads: function() {
        return Leads.find({}, {sort: {createdAt: 1}});
    },
})
{{#each lead in leads}}
    <p>{{lead.propertyName}}<p>
{{/each}}