Unsubscribing from an old subscription?


#1

I’m trying to implement pagination in my app without using external libraries and I’m running into issues. Here’s my template.

{{#if Template.subscriptionsReady}}
  {{#each posts}}
    {{> postPreview}}
    <hr>
  {{/each}}
{{else}}
  {{> spinner}}
{{/if}}

<!-- Pager -->
<ul class="pager">
  {{#if showNewerPostsButton}}
    <li class="previous previousButton">
      <a>&larr; Newer Posts </a>
    </li>
  {{/if}}
  {{#if showOlderPostsButton}}
    <li class="next nextButton">
      <a>Older Posts &rarr;</a>
    </li>
  {{/if}}
</ul>

Basically the way it’s supposed to work is that when the user clicks one of the buttons, the server is supposed to get the next items in the record set and ‘ideally’ update the subscription to match. I’m having problems making the subscription record set match what I want: It looks like Meteor keeps collecting records with every new subscription.

Template.postsList.events({
  'click .nextButton': (e) => {
    let page = parseInt(FlowRouter.getParam('page'));
    if (page === undefined || isNaN(page)) {
      page = 0;
    }
    FlowRouter.setParams({ page: page + 1 });
  },
  'click .previousButton': (e) => {
    let page = parseInt(FlowRouter.getParam('page'));
    if (page === undefined || isNaN(page) || page < 1) {
      page = 1;
    }

    FlowRouter.setParams({ page: page - 1 });
  },
});

Right now, when I click the button, what I’m pretty sure is happening is Meteor is seeing my change to FlowRouter params and runs my template.autorun (below). My first thought to resolving this problem was to use Meteor.subscribe()'s returned handle to handle.stop() the subscription. Unfortunately, it appears that inside this function, both this.subscribe() and Meteor.subscribe() don’t return an actual handle that can be used to handle.stop() the subscription and instead returns a subscriptionId string. I don’t know how to use this string or if it’s even possible to use it.

Template.postsList.onCreated(function () {
  var self = this;
  self.autorun(function () {
    var page = parseInt(FlowRouter.getParam('page'));
    if (page == undefined || page < 0 || isNaN(page)) {
      page = 0;
    }
    var handle = Session.get('postPreviewsHandle');
    if (handle) {
      console.dir(handle);
      handle.stop(); // Error! Function doesn't exist because this is only a string
    }

    // Meteor.subscribe() behaves the same way here
    handle = self.subscribe('postPreviews', page);
    
    Session.set('postPreviewsHandle', handle);
  });
});

Am I doing this right? Or is there a better way someone could share…?