I am using React and withTracker to run a reactive subscription. The subscription accepts one reactive arguments, so when it changes, subscription is run again. It works fine, but I am wondering if I can optimize it.
Everytime my reactive argument changes, withTracker runs again, so publication is run again too. I’ve notice that when publication is run again, it actually stops and create a new one. In the new publication, the mongoDB query is entirely run again, even if DDP just send me new records then.
Can I avoid the subscription to stop everytime my reactive argument changes?
This is the code I used to test, it is a simple blog home page that displays last articles with an infinite-scroll system:
Container:
import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import { ReactiveVar } from 'meteor/reactive-var';
import PublishedArticles from '../../api/published-articles/published-articles';
import HomePage from '../components/HomePage';
const limit = new ReactiveVar(5);
const HomeContainer = withTracker(() => {
Meteor.subscribe('publishedArticles.infinite', { limit: limit.get() });
const seeMore = () => {
limit.set(limit.get() + 1);
};
return { seeMore, articles: PublishedArticles.find().fetch() };
})(HomePage);
export default HomeContainer;
Publication (low level API for debugging purposes):
import { Meteor } from 'meteor/meteor';
import PublishedArticles from '../../published-articles';
Meteor.publish('publishedArticles.infinite', function({ limit }) {
let count = 0;
const handle = PublishedArticles.find(
{},
{ fields: { _id: 1, title: 1, content: 1 }, limit },
).observeChanges({
added: (id, fields) => {
count += 1;
console.log(count);
this.added('publishedArticles', id, fields);
},
});
this.ready();
this.onStop(() => handle.stop());
});