Karol Selak
Karol Selak

Reputation: 4804

What is necessary to fire Tracker's autorun function?

I have such an example Meteor app:

import React from 'react';
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import { Mongo } from 'meteor/mongo';

Things = new Mongo.Collection('things');

if (Meteor.isClient) {
  Meteor.startup(() => {
    Tracker.autorun(() => {
      console.log('AUTORUN');
    });
    Meteor.subscribe('things');
    render(<div>Hello world</div>, document.getElementById('app'));
  });
} else if (Meteor.isServer) {
  Meteor.publish('things', function() {
    return Things.find({});
  });
}

I expected that while modifying one of documents in my Things collection the autorun function should be fired, but it isn't. So my question is: what conditions should be met to fire autorun function after modifying subscribed data?

Upvotes: 0

Views: 73

Answers (1)

ghybs
ghybs

Reputation: 53370

You have 2 mistakes here:

  1. A Tracker.autorun detects changes only within the function that it wraps (the one as its argument). Here you have only a console.log, which is not a reactive source that the autorun can watch.

  2. There is a difference between the Pub/Sub mechanism and the documents themselves. Your Subscription will not change when you modify documents. But if you place a Collection query within your autorun, then the cursor returned by the query is a reactive source that is changed when the documents are modified.

So you could do something like:

Meteor.startup(() => {
    Meteor.subscribe('things');

    Tracker.autorun(() => {
        Things.find(); // <= Reactive source
        console.log('AUTORUN');
    });
});

Upvotes: 2

Related Questions